Android开发笔记

线程或者异步相关:

判断是否工作在主线程上

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

内存相关:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//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();
}
}

磁盘相关:

获取磁盘可用空间大小:

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

手机工作状态:

是否工作在飞行模式:

1
2
3
4
5
//From Picasso
static boolean isAirplaneModeOn(Context context) {
ContentResolver contentResolver = context.getContentResolver();
return Settings.System.getInt(contentResolver, AIRPLANE\_MODE\_ON, 0) != 0;
}

获取当前的网络状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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());

当然,需要权限:

1
2
<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>

权限

检查是否具有某项权限:

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