Android开发常用代码片段

 
 
 
 
//获取drawable对象
public static Drawable getDrawable(Context context,int id){
Resource res = context.getResource();
Drawable drawable = res.getDrawable(id);
return drawable;
}
//drawable转bitmap对象
public static Bitmap getBitmap(Context context,int id){
Drawable drawable = getDrawable(context,id);
BitmapDrawable bd =(BitmapDrawable)drawable;
Bitmap bitmap = bd.getBitmap();
}
public static Bitmap drawableToBitmap(Drawable drawable) {
      int w = drawable.getIntrinsicWidth();
      int h = drawable.getIntrinsicHeight();
      System.out.println("Drawable转Bitmap");
      Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;
      Bitmap bitmap = Bitmap.createBitmap(w, h, config);
      //注意,下面三行代码要用到,否则在View或者SurfaceView里的canvas.drawBitmap会看不到图
      Canvas canvas = new Canvas(bitmap);
      drawable.setBounds(0, 0, w, h);
      drawable.draw(canvas);
      return bitmap;
}
//Bitmap 转换成 Drawable
使用 BitmapDrawable 对 Bitmap 进行强制转换
public static Drawable bitmapToDrawable(Bitmap bmp){
    Drawable drawable = new BitmapDrawable(bmp);
	return drawable;
}
//判断当前App处于前台还是后台状态
public static boolean isApplicationBackground( final Context context) {

     ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
     @SuppressWarnings ( "deprecation" )
     List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks( 1 );
     if (!tasks.isEmpty()) {
       ComponentName topActivity = tasks.get( 0 ).topActivity;
       if (!topActivity.getPackageName().equals(context.getPackageName())) {
         return true ;
       }
     }
     return false ;
   }
//需要添加权限
<uses-permission android:name= "android.permission.GET_TASKS" />

//Bitmap 转换成 byte[]
public static byte[] getBitmapBytes(Bitmap bitmap){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();   
}
//byte[] 转化成 Bitmap
public static Bitmap BytesToBimap(byte[] b) {
    if (b.length != 0) {
        return BitmapFactory.decodeByteArray(b, 0, b.length);
    } else {
        return null;
    }
}
//判断当前手机是否处于锁屏(睡眠)状态
public static boolean isSleeping(Context context) {
     KeyguardManager kgMgr = (KeyguardManager) context
         .getSystemService(Context.KEYGUARD_SERVICE);
     boolean isSleeping = kgMgr.inKeyguardRestrictedInputMode();
     return isSleeping;
   }
//判断当前是否有网络连接
public static boolean isOnline(Context context) {
     ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE);
     NetworkInfo info = manager.getActiveNetworkInfo();
     if (info != null && info.isConnected()) {
       return true ;
     }
     return false ;
   }
//判断当前是否是WIFI连接状态
public static boolean isWifiConnected(Context context) {
   ConnectivityManager connectivityManager = (ConnectivityManager) context
       .getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
   if (wifiNetworkInfo.isConnected()) {
     return true ;
   }
   return false ;
}
//安装APK
public static void installApk(Context context, File file) {
   Intent intent = new Intent();
   intent.setAction( "android.intent.action.VIEW" );
   intent.addCategory( "android.intent.category.DEFAULT" );

   intent.setType( "application/vnd.android.package-archive" );

   intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive" );
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

   context.startActivity(intent);
}

//判断当前设备是否为手机
public static boolean isPhone(Context context) {

   TelephonyManager telephony = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE);

   if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
     return false ;
   } else {
     return true ;
   }
}
//获取当前设备宽高,单位px
@SuppressWarnings ( "deprecation" )
public static int getDeviceWidth(Context context) {
   WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
   return manager.getDefaultDisplay().getWidth();
}

@SuppressWarnings ( "deprecation" )
public static int getDeviceHeight(Context context) {
   WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
   return manager.getDefaultDisplay().getHeight();
}
//获取当前设备的IMEI,需要与上面的isPhone()一起使用
@TargetApi (Build.VERSION_CODES.CUPCAKE)
public static String getDeviceIMEI(Context context) {
   String deviceId;
   if (isPhone(context)) {
     TelephonyManager telephony = (TelephonyManager) context
         .getSystemService(Context.TELEPHONY_SERVICE);
     deviceId = telephony.getDeviceId();
   } else {
     deviceId = Settings.Secure.getString(context.getContentResolver(),
         Settings.Secure.ANDROID_ID);
   }
   return deviceId;
}
//获取当前设备的MAC地址
public static String getMacAddress(Context context) {
   String macAddress;
   WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
   WifiInfo info = wifi.getConnectionInfo();
   macAddress = info.getMacAddress();
   if ( null == macAddress) {
     return "" ;
   }
   macAddress = macAddress.replace( ":" , "" );
   return macAddress;
}
//获取当前程序的版本号
public static String getAppVersion(Context context) {
   String version = "0" ;
   try {
     version = context.getPackageManager().getPackageInfo(
         context.getPackageName(), 0 ).versionName;
   } catch (PackageManager.NameNotFoundException e) {
     e.printStackTrace();
   }
   return version;
}
//收集设备信息,用于信息统计分析
public static Properties collectDeviceInfo(Context context) {
     Properties mDeviceCrashInfo = new Properties();
     try {
       PackageManager pm = context.getPackageManager();
       PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
           PackageManager.GET_ACTIVITIES);
       if (pi != null ) {
         mDeviceCrashInfo.put(VERSION_NAME,pi.versionName == null ? "not set" : pi.versionName);
         mDeviceCrashInfo.put(VERSION_CODE, pi.versionCode);
       }
     } catch (PackageManager.NameNotFoundException e) {
       Log.e(TAG, "Error while collect package info" , e);
     }
     Field[] fields = Build. class .getDeclaredFields();
     for (Field field : fields) {
       try {
         field.setAccessible( true );
         mDeviceCrashInfo.put(field.getName(), field.get( null ));
       } catch (Exception e) {
         Log.e(TAG, "Error while collect crash info" , e);
       }
     }
     return mDeviceCrashInfo;
   }

public static String collectDeviceInfoStr(Context context) {
     Properties prop = collectDeviceInfo(context);
     Set deviceInfos = prop.keySet();
     StringBuilder deviceInfoStr = new StringBuilder( "{\n" );
     for (Iterator iter = deviceInfos.iterator(); iter.hasNext();) {
       Object item = iter.next();
       deviceInfoStr.append( "\t\t\t" + item + ":" + prop.get(item)+ ", \n" );
     }
     deviceInfoStr.append( "}" );
     return deviceInfoStr.toString();
   }
//是否有SD卡
public static boolean haveSDCard() {
     return android.os.Environment.getExternalStorageState().equals(
         android.os.Environment.MEDIA_MOUNTED);
}
//动态隐藏软键盘
@TargetApi (Build.VERSION_CODES.CUPCAKE)
   public static void hideSoftInput(Activity activity) {
     View view = activity.getWindow().peekDecorView();
     if (view != null ) {
       InputMethodManager inputmanger = (InputMethodManager) activity
           .getSystemService(Context.INPUT_METHOD_SERVICE);
       inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0 );
     }
   }

@TargetApi (Build.VERSION_CODES.CUPCAKE)
public static void hideSoftInput(Context context, EditText edit) {
     edit.clearFocus();
     InputMethodManager inputmanger = (InputMethodManager) context
         .getSystemService(Context.INPUT_METHOD_SERVICE);
     inputmanger.hideSoftInputFromWindow(edit.getWindowToken(), 0 );
}
//动态显示软键盘
@TargetApi (Build.VERSION_CODES.CUPCAKE)
public static void showSoftInput(Context context, EditText edit) {
     edit.setFocusable( true );
     edit.setFocusableInTouchMode( true );
     edit.requestFocus();
     InputMethodManager inputManager = (InputMethodManager) context
         .getSystemService(Context.INPUT_METHOD_SERVICE);
     inputManager.showSoftInput(edit, 0 );
   }
//动态显示或者是隐藏软键盘
@TargetApi (Build.VERSION_CODES.CUPCAKE)
public static void toggleSoftInput(Context context, EditText edit) {
     edit.setFocusable( true );
     edit.setFocusableInTouchMode( true );
     edit.requestFocus();
     InputMethodManager inputManager = (InputMethodManager) context
         .getSystemService(Context.INPUT_METHOD_SERVICE);
     inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0 );
   }
//主动回到Home,后台运行
public static void goHome(Context context) {
     Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
     mHomeIntent.addCategory(Intent.CATEGORY_HOME);
     mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
         | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
     context.startActivity(mHomeIntent);
   }
//获取状态栏高度
//注意,要在onWindowFocusChanged中调用,在onCreate中获取高度为0
@TargetApi (Build.VERSION_CODES.CUPCAKE)
public static int getStatusBarHeight(Activity activity) {
   Rect frame = new Rect();
   activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
     return frame.top;
   }
//获取状态栏高度+标题栏(ActionBar)高度
//(注意,如果没有ActionBar,那么获取的高度将和上面的是一样的,只有状态栏的高度)
public static int getTopBarHeight(Activity activity) {
     return activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
   }
//px-dp转换
public static int dip2px(Context context, float dpValue) {
   final float scale = context.getResources().getDisplayMetrics().density;
   return ( int ) (dpValue * scale + 0 .5f);
}

public static int px2dip(Context context, float pxValue) {
   final float scale = context.getResources().getDisplayMetrics().density;
   return ( int ) (pxValue / scale + 0 .5f);
}
//px-sp转换
public static int px2sp(Context context, float pxValue) {
     final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
     return ( int ) (pxValue / fontScale + 0 .5f);
   }

public static int sp2px(Context context, float spValue) {
     final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
     return ( int ) (spValue * fontScale + 0 .5f);
   }
//把一个毫秒数转化成时间字符串
//格式为小时/分/秒/毫秒(如:24903600 –> 06小时55分03秒600毫秒)
/**
    * @param millis
    *            要转化的毫秒数。
    * @param isWhole
    *            是否强制全部显示小时/分/秒/毫秒。
    * @param isFormat
    *            时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。
    * @return 返回时间字符串:小时/分/秒/毫秒的格式(如:24903600 --> 06小时55分03秒600毫秒)。
    */
   public static String millisToString( long millis, boolean isWhole,boolean isFormat) {
     String h = "" ;
     String m = "" ;
     String s = "" ;
     String mi = "" ;
     if (isWhole) {
       h = isFormat ? "00小时" : "0小时" ;
       m = isFormat ? "00分" : "0分" ;
       s = isFormat ? "00秒" : "0秒" ;
       mi = isFormat ? "00毫秒" : "0毫秒" ;
     }
     long temp = millis;
     long hper = 60 * 60 * 1000 ;
     long mper = 60 * 1000 ;
     long sper = 1000 ;
     if (temp / hper > 0 ) {
       if (isFormat) {
         h = temp / hper < 10 ? "0" + temp / hper : temp / hper + "" ;
       } else {
         h = temp / hper + "" ;
       }
       h += "小时" ;
     }
     temp = temp % hper;
     if (temp / mper > 0 ) {
       if (isFormat) {
         m = temp / mper < 10 ? "0" + temp / mper : temp / mper + "" ;
       } else {
         m = temp / mper + "" ;
       }
       m += "分" ;
     }
     temp = temp % mper;
     if (temp / sper > 0 ) {
       if (isFormat) {
         s = temp / sper < 10 ? "0" + temp / sper : temp / sper + "" ;
       } else {
         s = temp / sper + "" ;
       }
       s += "秒" ;
     }
     temp = temp % sper;
     mi = temp + "" ;
     if (isFormat) {
       if (temp < 100 && temp >= 10 ) {
         mi = "0" + temp;
       }
       if (temp < 10 ) {
         mi = "00" + temp;
       }
     }
     mi += "毫秒" ;
     return h + m + s + mi;
   }
格式为小时/分/秒/毫秒(如:24903600 –> 06小时55分03秒)。
/**
    *
    * @param millis
    *            要转化的毫秒数。
    * @param isWhole
    *            是否强制全部显示小时/分/秒/毫秒。
    * @param isFormat
    *            时间数字是否要格式化,如果true:少位数前面补全;如果false:少位数前面不补全。
    * @return 返回时间字符串:小时/分/秒/毫秒的格式(如:24903600 --> 06小时55分03秒)。
    */
   public static String millisToStringMiddle( long millis, boolean isWhole,
       boolean isFormat) {
     return millisToStringMiddle(millis, isWhole, isFormat, "小时" , "分钟" , "秒" );
   }

   public static String millisToStringMiddle( long millis, boolean isWhole,
       boolean isFormat, String hUnit, String mUnit, String sUnit) {
     String h = "" ;
     String m = "" ;
     String s = "" ;
     if (isWhole) {
       h = isFormat ? "00" + hUnit : "0" + hUnit;
       m = isFormat ? "00" + mUnit : "0" + mUnit;
       s = isFormat ? "00" + sUnit : "0" + sUnit;
     }
     long temp = millis;
     long hper = 60 * 60 * 1000 ;
     long mper = 60 * 1000 ;
     long sper = 1000 ;
     if (temp / hper > 0 ) {
       if (isFormat) {
         h = temp / hper < 10 ? "0" + temp / hper : temp / hper + "" ;
       } else {
         h = temp / hper + "" ;
       }


猜你喜欢

转载自blog.csdn.net/zhuxingchong/article/details/79459318