1.android dp和px之间转换public class DensityUtil { /** * 根据手机的分辨率从 dip 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
2.android 对话框样式

<style name="MyDialog" parent="@android:Theme.Dialog"> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@color/ha</item> </style>
3.android 根据uri获取路径

Uri uri = data.getData(); String[] proj = { MediaStore.Images.Media.DATA }; Cursor actualimagecursor = managedQuery(uri,proj,null,null,null); int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); actualimagecursor.moveToFirst(); String img_path = actualimagecursor.getString(actual_image_column_index); File file = new File(img_path); 
4.android 根据uri获取真实路径

public static String getRealFilePath( final Context context, final Uri uri ) { if ( null == uri ) return null; final String scheme = uri.getScheme(); String data = null; if ( scheme == null ) data = uri.getPath(); else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) { data = uri.getPath(); } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) { Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null ); if ( null != cursor ) { if ( cursor.moveToFirst() ) { int index = cursor.getColumnIndex( ImageColumns.DATA ); if ( index > -1 ) { data = cursor.getString( index ); } } cursor.close(); } } return data; }
5.android 还原短信
ContentValues values = new ContentValues(); values.put("address", "123456789"); values.put("body", "haha"); values.put("date", "135123000000"); getContentResolver().insert(Uri.parse("content://sms/sent"), values);
6.android 横竖屏切换

< activity android:name="MyActivity" android:configChanges="orientation|keyboardHidden"> public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { //加入横屏要处理的代码 }else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { //加入竖屏要处理的代码 } } 
7.android 获取mac地址

1、<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 2、private String getLocalMacAddress() { WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifi.getConnectionInfo(); return info.getMacAddress(); } 8.android 获取sd卡状态/** 获取存储卡路径 */ File sdcardDir=Environment.getExternalStorageDirectory(); /** StatFs 看文件系统空间使用情况 */ StatFs statFs=new StatFs(sdcardDir.getPath()); /** Block 的 size*/ Long blockSize=statFs.getBlockSize(); /** 总 Block 数量 */ Long totalBlocks=statFs.getBlockCount(); /** 已使用的 Block 数量 */ Long availableBlocks=statFs.getAvailableBlocks(); 
9.android 获取标题栏状态栏高度

Android获取状态栏和标题栏的高度 1.Android获取状态栏高度: decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。 于是,我们就可以算出状态栏的高度了。 Rect frame = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; 2.获取标题栏高度: getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。 int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); //statusBarHeight是上面所求的状态栏的高度 int titleBarHeight = contentTop - statusBarHeight 例子代码: package com.cn.lhq; import android.app.Activity; import android.graphics.Rect; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.widget.ImageView; public class Main extends Activity { ImageView iv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); iv = (ImageView) this.findViewById(R.id.ImageView01); iv.post(new Runnable() { public void run() { viewInited(); } }); Log.v("test", "== ok =="); } private void viewInited() { Rect rect = new Rect(); Window window = getWindow(); iv.getWindowVisibleDisplayFrame(rect); int statusBarHeight = rect.top; int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT) .getTop(); int titleBarHeight = contentViewTop - statusBarHeight; // 测试结果:ok之后 100多 ms 才运行了 Log.v("test", "=-init-= statusBarHeight=" + statusBarHeight + " contentViewTop=" + contentViewTop + " titleBarHeight=" + titleBarHeight); } } <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/ImageView01" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
10.android 获取各种窗体高度

//取得窗口属性 getWindowManager().getDefaultDisplay().getMetrics(dm); //窗口的宽度 int screenWidth = dm.widthPixels; //窗口高度 int screenHeight = dm.heightPixels; textView = (TextView)findViewById(R.id.textView01); textView.setText("屏幕宽度: " + screenWidth + "\n屏幕高度: " + screenHeight); 二、获取状态栏高度 decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。 于是,我们就可以算出状态栏的高度了。 view plain Rect frame = new Rect(); getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; 三、获取标题栏高度 getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。 view plain int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); //statusBarHeight是上面所求的状态栏的高度 int titleBarHeight = contentTop - statusBarHeight11.android 禁用home键盘 问题的提出 Android Home键系统负责监听,捕获后系统自动处理。有时候,系统的处理往往不随我们意,想自己处理点击Home后的事件,那怎么办? 问题的解决 先禁止Home键,再在onKeyDown里处理按键值,点击Home键的时候就把程序关闭,或者随你XXOO。 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if(KeyEvent.KEYCODE_HOME==keyCode) android.os.Process.killProcess(android.os.Process.myPid()); return super.onKeyDown(keyCode, event); } @Override public void onAttachedToWindow() { // TODO Auto-generated method stub this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } 加权限禁止Home键 <uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
12.android 开机启动

public class StartupReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent startupintent = new Intent(context,StrongTracks.class); startupintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(startupintent); } } 2)<receiver android:name=".StartupReceiver"> <intent-filter> <!-- 系统启动完成后会调用 --> <action android:name="android.intent.action.BOOT_COMPLETED"> </action> </intent-filter> </receiver> 13.android 控制对话框位置

window =dialog.getWindow();//    得到对话框的窗口. WindowManager.LayoutParams wl = window.getAttributes(); wl.x = x;//这两句设置了对话框的位置.0为中间 wl.y =y; wl.width =w; wl.height =h; wl.alpha =0.6f;// 这句设置了对话框的透明度 14.android 挪动dialog的位置

Window mWindow = dialog.getWindow(); WindowManager.LayoutParams lp = mWindow.getAttributes(); lp.x = 10; //新位置X坐标 lp.y = -100; //新位置Y坐标 dialog.onWindowAttributesChanged(lp);15.android 判断网络状态<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> private boolean getNetWorkStatus() { boolean netSataus = false; ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); cwjManager.getActiveNetworkInfo(); if (cwjManager.getActiveNetworkInfo() != null) { netSataus = cwjManager.getActiveNetworkInfo().isAvailable(); } if (!netSataus) { Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络") .setMessage("是否对网络进行设置?"); b.setPositiveButton("是", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent mIntent = new Intent("/"); ComponentName comp = new ComponentName( "com.android.settings", "com.android.settings.WirelessSettings"); mIntent.setComponent(comp); mIntent.setAction("android.intent.action.VIEW"); startActivityForResult(mIntent,0); } }).setNeutralButton("否", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }).show(); } return netSataus; } 16.android 设置apn

ContentValues values = new ContentValues(); values.put(NAME, "CMCC cmwap"); values.put(APN, "cmwap"); values.put(PROXY, "10.0.0.172"); values.put(PORT, "80"); values.put(MMSPROXY, ""); values.put(MMSPORT, ""); values.put(USER, ""); values.put(SERVER, ""); values.put(PASSWORD, ""); values.put(MMSC, ""); values.put(TYPE, ""); values.put(MCC, "460"); values.put(MNC, "00"); values.put(NUMERIC, "46000"); reURI = getContentResolver().insert(Uri.parse("content://telephony/carriers"), values); //首选接入点"content://telephony/carriers/preferapn"17.android 调节屏幕亮度

public void setBrightness(int level) { ContentResolver cr = getContentResolver(); Settings.System.putInt(cr, "screen_brightness", level); Window window = getWindow(); LayoutParams attributes = window.getAttributes(); float flevel = level; attributes.screenBrightness = flevel / 255; getWindow().setAttributes(attributes); } 
18.android 重启

第一,root权限,这是必须的 第二,Runtime.getRuntime().exec("su -c reboot"); 第三,模拟器上运行不出来,必须真机 第四,运行时会提示你是否加入列表 , 同意就好
19.android 资源uri

android.resource://com.packagename/raw/xxxx

20.android隐藏软键盘

setContentView(R.layout.activity_main); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
21.android隐藏以及显示软键盘以及不自动弹出键盘的方法

1、//隐藏软键盘 ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 2、//显示软键盘,控件ID可以是EditText,TextView ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(控件ID, 0); 22.BitMap、Drawable、inputStream及byte[] 互转

(1) BitMap to inputStream: ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); InputStream isBm = new ByteArrayInputStream(baos .toByteArray()); (2)BitMap to byte[]: Bitmap defaultIcon = BitmapFactory.decodeStream(in); ByteArrayOutputStream stream = new ByteArrayOutputStream(); defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] bitmapdata = stream.toByteArray(); (3)Drawable to byte[]: Drawable d; // the drawable (Captain Obvious, to the rescue!!!) Bitmap bitmap = ((BitmapDrawable)d).getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, bitmap); byte[] bitmapdata = stream.toByteArray(); (4)byte[] to Bitmap : Bitmap bitmap =BitmapFactory.decodeByteArray(byte[], 0,byte[].length);23.发送指令

out = process.getOutputStream(); out.write(("am start -a android.intent.action.VIEW -n com.android.browser/com.android.browser.BrowserActivity\n").getBytes()); out.flush(); InputStream in = process.getInputStream(); BufferedReader re = new BufferedReader(new InputStreamReader(in)); String line = null; while((line = re.readLine()) != null) { Log.d("conio","[result]"+line); }
24.Android判断GPS是否开启和强制帮用户打开GPS

http://blog.csdn.net/android_ls/article/details/8605931
 

引子:在我们的应用为用户提供定位服务时,通常想为用户提供精确点的定位服务,这是需要用户配合的。我们必须先检测用户手机的GPS当前是否打开,若没打开则弹出对话框提示。用户若不配合我们也没办法,只能采用基站定位方式。如果我们的应用必须用户打开GPS才可使用,这时流氓一点的做法,就是强制帮用户打开GPS。
阐明概念:       
        定位服务GPS:全球卫星定位系统,使用24个人造卫星所形成的网络来三角定位接受器的位置,并提供经纬度坐标。虽然GPS提供绝佳的位置的精确度,但定位的位置需要在可看见人造卫星或轨道所经过的地方。
       定位服务AGPS:辅助全球卫星定位系统(英语:Assisted Global Positioning System,简称:AGPS)是一种GPS的运行方式。它可以利用手机基地站的资讯,配合传统GPS卫星,让定位的速度更快。用中文来说应该是网络辅助GPS定位系统。通俗的说AGPS是在以往通过卫星接受定位信号的同时结合移动运营的GSM或者CDMA网络机站的定位信息,就是一方面由具有AGPS的手机获取来自卫星的定位信息,而同时也要靠该手机透过中国移动的GPRS网络下载辅助的定位信息,两者相结合来完成定位。与传统GPS(GlobalPositioningSystem全球定位系统)首次定位要2、3分钟相比AGPS的首次定位时间最快仅需几秒钟,同时AGPS也彻底解决了普通GPS设备在室内无法获取定位信息的缺陷。
一、检测用户手机的GPS当前是否打开,,代码如下:
[java] view plaincopy
/** 
     * 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的 
     * @param context 
     * @return true 表示开启 
     */  
    public static final boolean isOPen(final Context context) {  
        LocationManager locationManager   
                                 = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
        // 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快)  
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);  
        // 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位)  
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);  
        if (gps || network) {  
            return true;  
        }  
  
        return false;  
    }  
二、强制帮用户打开GPS,代码如下:
[java] view plaincopy
/** 
     * 强制帮用户打开GPS 
     * @param context 
     */  
    public static final void openGPS(Context context) {  
        Intent GPSIntent = new Intent();  
        GPSIntent.setClassName("com.android.settings",  
                "com.android.settings.widget.SettingsAppWidgetProvider");  
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");  
        GPSIntent.setData(Uri.parse("custom:3"));  
        try {

PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();

} catch (CanceledException e) {  
            e.printStackTrace();  
        }  
    }  
三、在AndroidManifest.xml文件里需要添加的权限:
[html] view plaincopy
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />  
<uses-permission android:name="android.permission.INTERNET" />

Android编程实用代码合集的更多相关文章

  1. 转--Android学习笔记-实用代码合集

    http://blog.csdn.net/yf210yf/article/details/7295577 转载请注明原文出处:奔跑的蜗牛(袁方的技术博客)点击打开链接 一.当利用textview显示内 ...

  2. [ZZ] UIUC同学Jia-Bin Huang收集的计算机视觉代码合集

    UIUC同学Jia-Bin Huang收集的计算机视觉代码合集 http://blog.sina.com.cn/s/blog_4a1853330100zwgm.htmlv UIUC的Jia-Bin H ...

  3. 【转载】GitHub 标星 1.2w+,超全 Python 常用代码合集,值得收藏!

    本文转自逆袭的二胖,作者二胖 今天给大家介绍一个由一个国外小哥用好几年时间维护的 Python 代码合集.简单来说就是,这个程序员小哥在几年前开始保存自己写过的 Python 代码,同时把一些自己比较 ...

  4. 计算机视觉与模式识别代码合集第二版two

    Topic Name Reference code Image Segmentation Segmentation by Minimum Code Length AY Yang, J. Wright, ...

  5. 计算机视觉与模式识别代码合集第二版three

    计算机视觉与模式识别代码合集第二版three     Topic Name Reference code Optical Flow Horn and Schunck's Optical Flow   ...

  6. 老李分享:android app自动化测试工具合集

    老李分享:android app自动化测试工具合集   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课程感兴趣,请大家咨 ...

  7. WooCommerce代码合集整理

    本文整理了一些WooCommerce代码合集,方便查阅和使用,更是为了理清思路,提高自己.以下WooCommerce简称WC,代码放在主题的functions.php中即可. 修改首页和分类页面每页产 ...

  8. git常用代码合集

    git常用代码合集 1. Git init:初始化一个仓库 2. Git add 文件名称:添加文件到Git暂存区 3. Git commit -m “message”:将Git暂存区的代码提交到Gi ...

  9. 常用的js代码合集

    !function(util){ window.Utils = util(); }( function(){ //document_event_attributes var DEA = "d ...

随机推荐

  1. 方便大家学习的Node.js教程(一):理解Node.js

    理解Node.js 为了理解Node.js是如何工作的,首先你需要理解一些使得Javascript适用于服务器端开发的关键特性.Javascript是一门简单而又灵活的语言,这种灵活性让它能够经受住时 ...

  2. echarts断点连线问题 终级

    /** * * 测试关系图 graph type* */var coors1 = [['1', 0],['2', 182],['5', 290],['6', 330],['7', 310],['10' ...

  3. NOIP 2012 Day2

    tags: 扩展欧几里得 二分答案 查分 倍增 二分答案 贪心 NOIP categories: 信息学竞赛 总结 同余方程 借教室 疫情控制 同余方程 Solution 首先同余式可以转化为等式. ...

  4. django “如何”系列2:如何编写django-admin 命令

    应用可以使用manage.py注册自己的动作,例如,你可能想要为你即将发布的应用添加一个manage.py 操作.这节我们将为polls应用添加一个closepoll的命令 添加一个managemen ...

  5. QT 中怎样使得控件与 界面等比例变化

    转自:https://github.com/exoticknight/blog-post/blob/master/python-with-Qt-application-development/pyth ...

  6. MVC - 12.HtmlHelper

    1.动态生成URL @Url.Action("Index3","Stu3") @Url.RouteUrl("Default2", new { ...

  7. 前端读者 | ES6知识点概述

    本文来自 @羯瑞 整理 ES6,并不是一个新鲜的东西,ES7.ES8已经赶脚了.但是,东西不在于新,而在于总结. 变量的新定义 let 和 const 在ES6没有被普及时,我们会用的变量定义的方法是 ...

  8. CentOS上使用yum安装Apache

    关键词 CentOS上使用yum安装Apache 摘要 Apache在Linux系统中,其实叫“httpd”,它“无耻的”占据了官方名义!CentOS可以使用yum命令,非常简单和容易的安装Apach ...

  9. 启动WAMPSERVER出现计算机中丢失 MSVCR110.dll

    最近电脑因为系统损坏无法启动,不得已重装系统,也让PHP程序员雷雪松下决心坚决的抛弃XP系统.这样一来跟上时代的步伐,二来也为Win7的市场占有率和消灭IE7以下浏览器做点贡献.,作为一个PHP程序员 ...

  10. Jsonp方式和httpclient方式有什么区别?

    jsonp基于js,解决跨域问题,本质发起ajax情求但是Jsonp只支持get请求. 它不安全,它先解析js,然后发起ajax请求,然后获取到返回值,通过浏览器返回,最后解析. JQuery和Spr ...