Android开发笔记

线程或者异步相关:

判断是否工作在主线程上

//From Picasso
Looper.getMainLooper().getThread() == Thread.currentThread()

 

内存相关:

获取当前设备中,我们的应用所可以使用的Heap大小:

//From Picasso
ActivityManager am = getService(context, ACTIVITY_SERVICE);
boolean largeHeap = (context.getApplicationInfo().flags & FLAG_LARGE_HEAP) != 0;
int memoryClass = am.getMemoryClass();
if (largeHeap && SDK_INT >= HONEYCOMB) {
   memoryClass = ActivityManagerHoneycomb.getLargeMemoryClass(am);
}


@TargetApi(HONEYCOMB)
private static class ActivityManagerHoneycomb {
  static int getLargeMemoryClass(ActivityManager activityManager) {
  return activityManager.getLargeMemoryClass();
  }
}

 

磁盘相关:

获取磁盘可用空间大小:

//From Picasso
StatFs statFs = new StatFs(dir.getAbsolutePath());
long available = ((long) statFs.getBlockCount()) * statFs.getBlockSize();

 

手机工作状态:

是否工作在飞行模式:

//From Picasso
static boolean isAirplaneModeOn(Context context) {
  ContentResolver contentResolver = context.getContentResolver();
  return Settings.System.getInt(contentResolver, AIRPLANE_MODE_ON, 0) != 0;
}

 获取当前的网络状态:

public NetworkState getNetworkState(NetworkInfo info) {
  switch (info.getType()) {
    case ConnectivityManager.TYPE_WIFI:
    case ConnectivityManager.TYPE_WIMAX:
    case ConnectivityManager.TYPE_ETHERNET:
      return NetworkState.WIFI;
    case ConnectivityManager.TYPE_MOBILE:
      switch (info.getSubtype()) {
        case TelephonyManager.NETWORK_TYPE_LTE:  // 4G
        case TelephonyManager.NETWORK_TYPE_HSPAP:
        case TelephonyManager.NETWORK_TYPE_EHRPD:
          return NetworkState.MOBILE_4G;
        case TelephonyManager.NETWORK_TYPE_UMTS: // 3G
        case TelephonyManager.NETWORK_TYPE_CDMA:
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
          return NetworkState.MOBILE_3G;
        case TelephonyManager.NETWORK_TYPE_GPRS: // 2G
        case TelephonyManager.NETWORK_TYPE_EDGE:
          return NetworkState.MOBILE_2G;
      }
      break;
    default:
      return NetworkState.NOTCONNECTED;
    }
  return NetworkState.NOTCONNECTED;
}

  ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo info = connectivityManager.getActiveNetworkInfo();
  Log.i(TAG, getNetworkState(info).toString());

当然,需要权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission><uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

权限

检查是否具有某项权限:

static boolean hasPermission(Context context, String permission) {
  return context.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}

 

About: happyhls


发表评论

电子邮件地址不会被公开。 必填项已用*标注