android实用工具类分享(获取内存/检查网络/屏幕高度/手机分辨率

2019-12-10 20:07:35王振洲

  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);
 }

 /**
  * 查询手机内非系统应用
  * 
  * @param context
  * @return
  */
 public static List<PackageInfo> getAllApps(Context context) {

  List<PackageInfo> apps = new ArrayList<PackageInfo>();
  PackageManager pManager = context.getPackageManager();
  // 获取手机内所有应用
  List<PackageInfo> paklist = pManager.getInstalledPackages(0);
  for (int i = 0; i < paklist.size(); i++) {
   PackageInfo pak = (PackageInfo) paklist.get(i);
   // 判断是否为非系统预装的应用程序
   if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
    // customs applications
    apps.add(pak);
   }
  }
  return apps;
 }

 public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
  int w = bitmap.getWidth();
  int h = bitmap.getHeight();
  Matrix matrix = new Matrix();
  float scaleWidth = ((float) width / w);
  float scaleHeight = ((float) height / h);
  matrix.postScale(scaleWidth, scaleHeight);
  Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
  return newbmp;
 }

 /**
  * 获取版本号和版本次数
  * 
  * @param context
  * @return
  */
 public static String getVersionCode(Context context, int type) {

  try {

   PackageInfo pi = context.getPackageManager().getPackageInfo(
     context.getPackageName(), 0);
   if (type == 1) {

    return String.valueOf(pi.versionCode);
   } else {

    return pi.versionName;
   }
  } catch (NameNotFoundException e) {

   e.printStackTrace();
   return null;
  }
 }