在Activity请求许可
android.permission.PACKAGE_USAGE_STATS不是普通权限,不能简单请求。为了检查是否已授予权限,请检查:
AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
android.os.Process.myUid(), getPackageName());
if (mode == AppOpsManager.MODE_ALLOWED) {
return true;
}
要请求此权限,只需致电Intent:
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
还需要另一个权限:Manifest.permission.READ_PHONE_STATE。但是,这是正常的权限,所以可以是requested as any other permission
使用NetworkStatsManager:
要获取它的参考,请调用:
NetworkStatsManager networkStatsManager = (NetworkStatsManager) getApplicationContext().getSystemService(Context.NETWORK_STATS_SERVICE);
从NetworkStatsManager 检索到的所有内容都打包到Buckets 中。这只是一个简单的 POJO,用于保存数据。
全球:
要获得 WiFi 的总体使用情况:
NetworkStats.Bucket bucket;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI,
"",
0,
System.currentTimeMillis());
} catch (RemoteException e) {
return -1;
}
来自NetworkStats.Bucket,可以调用两个方法来获取使用情况(以Bps为单位):
bucket.getRxBytes();
bucket.getTxBytes();
获取移动网络的数据比较困难。为了获得Bucket调用:
public long getAllRxBytesMobile(Context context) {
NetworkStats.Bucket bucket;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
0,
System.currentTimeMillis());
} catch (RemoteException e) {
return -1;
}
return bucket.getRxBytes();
}
//Here Manifest.permission.READ_PHONE_STATS is needed
private String getSubscriberId(Context context, int networkType) {
if (ConnectivityManager.TYPE_MOBILE == networkType) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSubscriberId();
}
return "";
}
应用:
要获取特定应用的数据,请阅读queryDetailsForUID的文档。
获取WiFi的包使用情况:
NetworkStats networkStats = null;
try {
networkStats = networkStatsManager.queryDetailsForUid(
ConnectivityManager.TYPE_WIFI,
"",
0,
System.currentTimeMillis(),
packageUid);
} catch (RemoteException e) {
return -1;
}
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStats.getNextBucket(bucket);
要获取 Mobile 的包使用情况:
NetworkStats networkStats = null;
try {
networkStats = networkStatsManager.queryDetailsForUid(
ConnectivityManager.TYPE_MOBILE,
getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
0,
System.currentTimeMillis(),
packageUid);
} catch (RemoteException e) {
return -1;
}
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStats.getNextBucket(bucket);
不幸的是,根据this piece of code,只有ConnectivityManager.TYPE_MOBILE和ConnectivityManager.TYPE_WIFI才能获得统计信息。