Android编程实用代码合集



1.android dp和px之间转换

[java]  view plain  copy
  1. public class DensityUtil {    
  2.     
  3.     /**  
  4.      * 根据手机的分辨率从 dip 的单位 转成为 px(像素)  
  5.      */    
  6.     public static int dip2px(Context context, float dpValue) {    
  7.         final float scale = context.getResources().getDisplayMetrics().density;    
  8.         return (int) (dpValue * scale + 0.5f);    
  9.     }    
  10.     
  11.     /**  
  12.      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp  
  13.      */    
  14.     public static int px2dip(Context context, float pxValue) {    
  15.         final float scale = context.getResources().getDisplayMetrics().density;    
  16.         return (int) (pxValue / scale + 0.5f);    
  17.     }    
  18. }    

2.android 对话框样式

[java]  view plain  copy
  1. <style name="MyDialog" parent="@android:Theme.Dialog">  
  2.     <item name="android:windowNoTitle">true</item>  
  3.     <item name="android:windowBackground">@color/ha</item>  
  4. </style>  

3.android 根据uri获取路径

[java]  view plain  copy
  1. Uri uri = data.getData();  
  2.   
  3. String[] proj = { MediaStore.Images.Media.DATA };  
  4.   
  5. Cursor actualimagecursor = managedQuery(uri,proj,null,null,null);  
  6.   
  7. int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
  8.   
  9. actualimagecursor.moveToFirst();  
  10.   
  11. String img_path = actualimagecursor.getString(actual_image_column_index);  
  12.   
  13. File file = new File(img_path);  

4.android 根据uri获取真实路径

[java]  view plain  copy
  1. public static String getRealFilePath( final Context context, final Uri uri ) {  
  2.   
  3.     if ( null == uri ) return null;  
  4.   
  5.     final String scheme = uri.getScheme();  
  6.     String data = null;  
  7.   
  8.     if ( scheme == null )  
  9.         data = uri.getPath();  
  10.     else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {  
  11.         data = uri.getPath();  
  12.     } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {  
  13.         Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, nullnullnull );  
  14.         if ( null != cursor ) {  
  15.             if ( cursor.moveToFirst() ) {  
  16.                 int index = cursor.getColumnIndex( ImageColumns.DATA );  
  17.                 if ( index > -1 ) {  
  18.                     data = cursor.getString( index );  
  19.                 }  
  20.             }  
  21.             cursor.close();  
  22.         }  
  23.     }  
  24.     return data;  
  25. }  

5.android 还原短信

[java]  view plain  copy
  1. ContentValues values = new ContentValues();  
  2. values.put("address""123456789");  
  3. values.put("body""haha");  
  4. values.put("date""135123000000");  
  5. getContentResolver().insert(Uri.parse("content://sms/sent"), values);  

6.android 横竖屏切换

[java]  view plain  copy
  1. < activity android:name="MyActivity"    
  2. android:configChanges="orientation|keyboardHidden">   
  3.   
  4.   
  5. public void onConfigurationChanged(Configuration newConfig) {    
  6.     
  7.    super.onConfigurationChanged(newConfig);    
  8.     
  9. if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {    
  10.            //加入横屏要处理的代码    
  11.     
  12. }else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {    
  13.     
  14.            //加入竖屏要处理的代码    
  15.     
  16. }    
  17.     
  18.     
  19. }    

7.android 获取mac地址

[java]  view plain  copy
  1. 1、<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>      
  2. 2private String getLocalMacAddress() {    
  3.     WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);    
  4.     WifiInfo info = wifi.getConnectionInfo();    
  5.     return info.getMacAddress();    
  6.   }    

8.android 获取sd卡状态

[java]  view plain  copy
  1. /** 获取存储卡路径 */   
  2. File sdcardDir=Environment.getExternalStorageDirectory();   
  3. /** StatFs 看文件系统空间使用情况 */   
  4. StatFs statFs=new StatFs(sdcardDir.getPath());   
  5. /** Block 的 size*/   
  6. Long blockSize=statFs.getBlockSize();   
  7. /** 总 Block 数量 */   
  8. Long totalBlocks=statFs.getBlockCount();   
  9. /** 已使用的 Block 数量 */   
  10. Long availableBlocks=statFs.getAvailableBlocks();   

9.android 获取标题栏状态栏高度

[java]  view plain  copy
  1. Android获取状态栏和标题栏的高度  
  2.   
  3. 1.Android获取状态栏高度:  
  4.   
  5. decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。  
  6.   
  7. 于是,我们就可以算出状态栏的高度了。  
  8.   
  9. Rect frame = new Rect();  
  10. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  11. int statusBarHeight = frame.top;  
  12.   
  13. 2.获取标题栏高度:  
  14.   
  15. getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。  
  16.   
  17. int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
  18. //statusBarHeight是上面所求的状态栏的高度  
  19. int titleBarHeight = contentTop - statusBarHeight  
  20.   
  21. 例子代码:  
  22.   
  23. package com.cn.lhq;  
  24. import android.app.Activity;  
  25. import android.graphics.Rect;  
  26. import android.os.Bundle;  
  27. import android.util.Log;  
  28. import android.view.Window;  
  29. import android.widget.ImageView;  
  30. public class Main extends Activity {  
  31.  ImageView iv;  
  32.  @Override  
  33.  public void onCreate(Bundle savedInstanceState) {  
  34.   super.onCreate(savedInstanceState);  
  35.   setContentView(R.layout.main);  
  36.   iv = (ImageView) this.findViewById(R.id.ImageView01);  
  37.   iv.post(new Runnable() {  
  38.    public void run() {  
  39.     viewInited();  
  40.    }  
  41.   });  
  42.   Log.v("test""== ok ==");  
  43.  }  
  44.  private void viewInited() {  
  45.   Rect rect = new Rect();  
  46.   Window window = getWindow();  
  47.   iv.getWindowVisibleDisplayFrame(rect);  
  48.   int statusBarHeight = rect.top;  
  49.   int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)  
  50.     .getTop();  
  51.   int titleBarHeight = contentViewTop - statusBarHeight;  
  52.   // 测试结果:ok之后 100多 ms 才运行了  
  53.   Log.v("test""=-init-= statusBarHeight=" + statusBarHeight  
  54.     + " contentViewTop=" + contentViewTop + " titleBarHeight="  
  55.     + titleBarHeight);  
  56.  }  
  57. }  
  58.   
  59.    
  60.   
  61. <?xml version="1.0" encoding="utf-8"?>  
  62. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  63.     android:orientation="vertical"  
  64.     android:layout_width="fill_parent"  
  65.     android:layout_height="fill_parent">  
  66.  <ImageView   
  67.   android:id="@+id/ImageView01"   
  68.   android:layout_width="wrap_content"   
  69.   android:layout_height="wrap_content"/>  
  70. </LinearLayout>  

10.android 获取各种窗体高度

[java]  view plain  copy
  1.   //取得窗口属性  
  2.         getWindowManager().getDefaultDisplay().getMetrics(dm);  
  3.           
  4.         //窗口的宽度  
  5.         int screenWidth = dm.widthPixels;  
  6.         //窗口高度  
  7.         int screenHeight = dm.heightPixels;  
  8.         textView = (TextView)findViewById(R.id.textView01);  
  9.         textView.setText("屏幕宽度: " + screenWidth + "\n屏幕高度: " + screenHeight);  
  10.   
  11. 二、获取状态栏高度  
  12. decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。   
  13. 于是,我们就可以算出状态栏的高度了。  
  14. view plain  
  15.   
  16.   
  17. Rect frame = new Rect();  
  18. getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  19. int statusBarHeight = frame.top;  
  20.   
  21.   
  22. 三、获取标题栏高度  
  23. getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。  
  24. view plain  
  25.   
  26.   
  27. int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();  
  28. //statusBarHeight是上面所求的状态栏的高度  
  29. int titleBarHeight = contentTop - statusBarHeight  

11.android 禁用home键盘

[java]  view plain  copy
  1.         问题的提出  
  2.          Android Home键系统负责监听,捕获后系统自动处理。有时候,系统的处理往往不随我们意,想自己处理点击Home后的事件,那怎么办?  
  3.   
  4.    
  5.   
  6.         问题的解决  
  7.          先禁止Home键,再在onKeyDown里处理按键值,点击Home键的时候就把程序关闭,或者随你XXOO。  
  8.   
  9.    
  10.   
  11. @Override  
  12.   
  13.  public boolean onKeyDown(int keyCode, KeyEvent event)  
  14.   
  15. // TODO Auto-generated method stub  
  16.   
  17.   if(KeyEvent.KEYCODE_HOME==keyCode)  
  18.   
  19.     android.os.Process.killProcess(android.os.Process.myPid());  
  20.   
  21.      return super.onKeyDown(keyCode, event);  
  22.   
  23.   }  
  24.   
  25.    
  26.   
  27. @Override  
  28.   
  29.  public void onAttachedToWindow()  
  30.   
  31.  { // TODO Auto-generated method stub  
  32.   
  33.     this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);  
  34.   
  35.     super.onAttachedToWindow();  
  36.   
  37.  }  
  38.   
  39.    
  40.   
  41.    
  42.   
  43. 加权限禁止Home键  
  44.   
  45. <uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>  

12.android 开机启动

[java]  view plain  copy
  1. public class StartupReceiver extends BroadcastReceiver {    
  2.     
  3.   @Override    
  4.   public void onReceive(Context context, Intent intent) {    
  5.     Intent startupintent = new Intent(context,StrongTracks.class);    
  6.     startupintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
  7.     context.startActivity(startupintent);    
  8.   }    
  9.     
  10. }    
  11. 2)<receiver    
  12. android:name=".StartupReceiver">    
  13. <intent-filter>    
  14.     <!-- 系统启动完成后会调用 -->    
  15.     <action    
  16.         android:name="android.intent.action.BOOT_COMPLETED">    
  17.     </action>    
  18. </intent-filter>    
  19. </receiver>   

13.android 控制对话框位置

[java]  view plain  copy
  1. window =dialog.getWindow();//    得到对话框的窗口.    
  2.      WindowManager.LayoutParams wl = window.getAttributes();    
  3.       wl.x = x;//这两句设置了对话框的位置.0为中间    
  4.       wl.y =y;    
  5.       wl.width =w;    
  6.       wl.height =h;    
  7.       wl.alpha =0.6f;// 这句设置了对话框的透明度     

14.android 挪动dialog的位置

[java]  view plain  copy
  1. Window mWindow = dialog.getWindow();    
  2. WindowManager.LayoutParams lp = mWindow.getAttributes();    
  3. lp.x = 10;   //新位置X坐标    
  4. lp.y = -100//新位置Y坐标    
  5. dialog.onWindowAttributesChanged(lp);  

15.android 判断网络状态

[java]  view plain  copy
  1. <uses-permission    
  2.     android:name="android.permission.ACCESS_NETWORK_STATE" />    
  3.     
  4.  private boolean getNetWorkStatus() {    
  5.     
  6.    boolean netSataus = false;    
  7.    ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);    
  8.     
  9.    cwjManager.getActiveNetworkInfo();    
  10.     
  11.    if (cwjManager.getActiveNetworkInfo() != null) {    
  12.    netSataus = cwjManager.getActiveNetworkInfo().isAvailable();    
  13.    }    
  14.     
  15.    if (!netSataus) {    
  16.    Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络")    
  17.    .setMessage("是否对网络进行设置?");    
  18.    b.setPositiveButton("是"new DialogInterface.OnClickListener() {    
  19.    public void onClick(DialogInterface dialog, int whichButton) {    
  20.    Intent mIntent = new Intent("/");    
  21.    ComponentName comp = new ComponentName(    
  22.    "com.android.settings",    
  23.    "com.android.settings.WirelessSettings");    
  24.    mIntent.setComponent(comp);    
  25.    mIntent.setAction("android.intent.action.VIEW");    
  26.    startActivityForResult(mIntent,0);     
  27.    }    
  28.    }).setNeutralButton("否"new DialogInterface.OnClickListener() {    
  29.    public void onClick(DialogInterface dialog, int whichButton) {    
  30.    dialog.cancel();    
  31.    }    
  32.    }).show();    
  33.    }    
  34.     
  35.    return netSataus;    
  36.    }    

16.android 设置apn

[java]  view plain  copy
  1. ContentValues values = new ContentValues();  
  2. values.put(NAME, "CMCC cmwap");  
  3. values.put(APN, "cmwap");  
  4. values.put(PROXY, "10.0.0.172");  
  5.   
  6. values.put(PORT, "80");  
  7. values.put(MMSPROXY, "");  
  8. values.put(MMSPORT, "");  
  9. values.put(USER, "");  
  10. values.put(SERVER, "");  
  11. values.put(PASSWORD, "");  
  12. values.put(MMSC, "");           
  13. values.put(TYPE, "");  
  14. values.put(MCC, "460");  
  15. values.put(MNC, "00");  
  16. values.put(NUMERIC, "46000");  
  17. reURI = getContentResolver().insert(Uri.parse("content://telephony/carriers"), values);  
  18.   
  19.   
  20. //首选接入点"content://telephony/carriers/preferapn"  

17.android 调节屏幕亮度

[java]  view plain  copy
  1. public void setBrightness(int level) {   
  2. ContentResolver cr = getContentResolver();   
  3. Settings.System.putInt(cr, "screen_brightness", level);   
  4. Window window = getWindow();   
  5. LayoutParams attributes = window.getAttributes();   
  6. float flevel = level;   
  7. attributes.screenBrightness = flevel / 255;   
  8. getWindow().setAttributes(attributes);   
  9. }   

18.android 重启

[java]  view plain  copy
  1. 第一,root权限,这是必须的   
  2. 第二,Runtime.getRuntime().exec("su -c reboot");   
  3. 第三,模拟器上运行不出来,必须真机   
  4. 第四,运行时会提示你是否加入列表 , 同意就好  

19.android 资源uri

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

20.android隐藏软键盘

[java]  view plain  copy
  1. setContentView(R.layout.activity_main);  
  2.         getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |  
  3.                 WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);  

21.android隐藏以及显示软键盘以及不自动弹出键盘的方法

[java]  view plain  copy
  1. 1//隐藏软键盘     
  2.   
  3. ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);     
  4.   
  5.     
  6.   
  7. 2//显示软键盘,控件ID可以是EditText,TextView     
  8.   
  9. ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(控件ID, 0);   

22.BitMap、Drawable、inputStream及byte[] 互转

[java]  view plain  copy
  1. 1) BitMap  to   inputStream:  
  2.     ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  3.     bm.compress(Bitmap.CompressFormat.PNG, 100, baos);  
  4.     InputStream isBm = new ByteArrayInputStream(baos .toByteArray());  
  5.    
  6.  (2)BitMap  to   byte[]:  
  7.   Bitmap defaultIcon = BitmapFactory.decodeStream(in);  
  8.   ByteArrayOutputStream stream = new ByteArrayOutputStream();  
  9.   defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);  
  10.   byte[] bitmapdata = stream.toByteArray();  
  11.  (3)Drawable  to   byte[]:  
  12.   Drawable d; // the drawable (Captain Obvious, to the rescue!!!)  
  13.   Bitmap bitmap = ((BitmapDrawable)d).getBitmap();  
  14.   ByteArrayOutputStream stream = new ByteArrayOutputStream();  
  15.   defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, bitmap);  
  16.   byte[] bitmapdata = stream.toByteArray();  
  17.    
  18. 4byte[]  to  Bitmap :  
  19.   Bitmap bitmap =BitmapFactory.decodeByteArray(byte[], 0,byte[].length);  

23.发送指令

[java]  view plain  copy
  1. out = process.getOutputStream();  
  2. out.write(("am start -a android.intent.action.VIEW -n com.android.browser/com.android.browser.BrowserActivity\n").getBytes());  
  3. out.flush();  
  4.   
  5. InputStream in = process.getInputStream();  
  6. BufferedReader re = new BufferedReader(new InputStreamReader(in));  
  7. String line = null;  
  8. while((line = re.readLine()) != null) {  
  9.     Log.d("conio","[result]"+line);  
  10. }  

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" />

转自: http://blog.csdn.net/waldmer/article/details/50427465
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值