Android 獲取應(yīng)用流量的使用情況有兩種方法
- TrafficStats
- NetworkStatsManager 是Android 6.0(API23)中新增加的類
這次我們使用的是第二種方法,記錄一下實(shí)現(xiàn)過程
首先說明NetworkStatsManager能提供哪些功能
- 區(qū)分 Wifi 和手機(jī)網(wǎng)絡(luò)的流量使用
- 查詢指定應(yīng)用的流量使用
- 查詢指定時間段的流量使用(當(dāng)天/當(dāng)月/總共)
- 區(qū)分接收和發(fā)送的流量使用
看下方法使用代碼
/**
* 本機(jī)使用的 wifi 總流量
*/
public long getAllBytesWifi() {
NetworkStats.Bucket bucket;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI,
"",
0,
System.currentTimeMillis());
} catch (RemoteException e) {
return -1;
}
//這里可以區(qū)分發(fā)送和接收
return bucket.getTxBytes() +bucket.getRxBytes() ;
}
/**
* 本機(jī)使用的 mobile 總流量
*/
public long getAllBytesMobile() {
NetworkStats.Bucket bucket;
try {
bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE,
getSubscriberId(context, ConnectivityManager.TYPE_MOBILE),
0,
System.currentTimeMillis());
} catch (RemoteException e) {
return -1;
}
//這里可以區(qū)分發(fā)送和接收
return bucket.getTxBytes() +bucket.getRxBytes() ;
}
private String getSubscriberId(Context context, int networkType) {
if (ConnectivityManager.TYPE_MOBILE == networkType) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return tm.getSubscriberId();
}
return "";
}
/**
* 獲取指定應(yīng)用 wifi 發(fā)送的當(dāng)天總流量
* @param packageUid 應(yīng)用的uid
* @return
*/
public long getPackageTxDayBytesWifi(int packageUid) {
NetworkStats networkStats = null;
try {
networkStats = networkStatsManager.queryDetailsForUid(
ConnectivityManager.TYPE_WIFI,
"",
getTimesmorning(),
System.currentTimeMillis(),
packageUid);
} catch (RemoteException e) {
return -1;
}
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
networkStats.getNextBucket(bucket);
return bucket.getTxBytes();
}
/**
* 獲取當(dāng)天的零點(diǎn)時間
*
* @return
*/
public static long getTimesmorning() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
return (cal.getTimeInMillis());
}
//獲得本月第一天0點(diǎn)時間
public static int getTimesMonthmorning() {
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
return (int) (cal.getTimeInMillis());
}
/**
* 根據(jù)包名獲取uid
* @param context 上下文
* @param packageName 包名
*/
public static int getUidByPackageName(Context context, String packageName) {
int uid = -1;
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_META_DATA);
uid = packageInfo.applicationInfo.uid;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return uid;
}
調(diào)用過程
//以上的方法封裝在了NetworkStatsHelper類里
public class NetworkStatsHelper {
NetworkStatsManager networkStatsManager;
int packageUid;
public NetworkStatsHelper(NetworkStatsManager networkStatsManager) {
this.networkStatsManager = networkStatsManager;
}
}
//初始化這個工具類
NetworkStatsManager networkStatsManager = (NetworkStatsManager) getSystemService(NETWORK_STATS_SERVICE);
helper = new NetworkStatsHelper(networkStatsManager);
循環(huán)遍歷應(yīng)用
PackageManager packageManager = getPackageManager();
final List<PackageInfo> applicationInfoList = packageManager.getInstalledPackages(0);
for (PackageInfo info : applicationInfoList) {
try {
PackageInfo pack = packageManager.getPackageInfo(info.packageName,PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = pack.requestedPermissions;
if (requestedPermissions == null)
continue;
if (info.applicationInfo.uid == 1000)
continue;
for (String str : requestedPermissions) {
if (str.equals("android.permission.INTERNET")) {
long mobileTodayRx = helper.getPackageDayRxBytesMobile(mContext, uid);
//...添加自己的代碼
break;
}
}
} catch (PackageManager.NameNotFoundException exception) {
exception.printStackTrace();
}
}
這里說明下為什么要過濾掉info.applicationInfo.uid == 1000
因?yàn)闆]有獲取uid == 1000的進(jìn)程的流量權(quán)限
好了現(xiàn)在說到權(quán)限伯病,下面就是需要配置的權(quán)限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.READ_NETWORK_USAGE_HISTORY" tools:ignore="ProtectedPermissions"/>
其中tools:ignore 就是忽略這個錯誤的意思则吟,不然它會報紅
僅僅在manifest里配置權(quán)限還是不夠的汇陆,還要動態(tài)申請
private boolean hasPermissionToReadNetworkStats() {
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
final 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;
}
requestReadNetworkStats();
return false;
}
// 打開“有權(quán)查看使用情況的應(yīng)用”頁面
private void requestReadNetworkStats() {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
}
OK晃财,到此就應(yīng)該能成功獲取流量統(tǒng)計信息了