- NetworkStatsManager 中增加 TYPE_ETHERNET 类型
private static NetworkTemplate createTemplate(int networkType, String subscriberId) {
final NetworkTemplate template;
switch (networkType) {
case ConnectivityManager.TYPE_MOBILE:
template = subscriberId == null
? NetworkTemplate.buildTemplateMobileWildcard()
: NetworkTemplate.buildTemplateMobileAll(subscriberId);
break;
case ConnectivityManager.TYPE_WIFI:
template = NetworkTemplate.buildTemplateWifiWildcard();
break;
case ConnectivityManager.TYPE_ETHERNET:
template = NetworkTemplate.buildTemplateEthernet();
break;
default:
throw new IllegalArgumentException("Cannot create template for network type "
+ networkType + ", subscriberId '"
+ NetworkIdentity.scrubSubscriberId(subscriberId) + "'.");
}
return template;
}
2 . 应用就可以按照一下调用
if(hasPermissionToReadNetworkStats()){
val networkStatsManager = getSystemService(NETWORK_STATS_SERVICE) as NetworkStatsManager
var networkStatsHelper = NetworkStatsHelper(networkStatsManager)
var bucket: NetworkStats.Bucket? = null
bucket = networkStatsManager.querySummaryForDevice(
ConnectivityManager.TYPE_ETHERNET
"",
0,
System.currentTimeMillis()
)
findViewById<TextView>(R.id.tv).text = "流量1为:${((bucket.rxBytes + bucket.txBytes)/1024/1024).toFloat()}"
networkStatsHelper.getEveryAppData(this);
}
private fun hasPermissionToReadNetworkStats(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true
}
val appOps = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
val mode = appOps.checkOpNoThrow(
AppOpsManager.OPSTR_GET_USAGE_STATS,
Process.myUid(), packageName
)
if (mode == AppOpsManager.MODE_ALLOWED) {
return true
}
requestReadNetworkStats()
return false
}
// 打开“有权查看使用情况的应用”页面
private fun requestReadNetworkStats() {
val intent = Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
startActivity(intent)
}
- 获取每个应用流量
public void getEveryAppData(MainActivity ma) throws RemoteException {
NetworkStats summaryStats;
long summaryRx = 0;
long summaryTx = 0;
NetworkStats.Bucket summaryBucket = new NetworkStats.Bucket();
long summaryTotal = 0;
summaryStats = networkStatsManager.querySummary(ConnectivityManager.TYPE_WIFI, "", 0, System.currentTimeMillis());
do {
summaryStats.getNextBucket(summaryBucket);
int summaryUid = summaryBucket.getUid();
Log.i(MainActivity.class.getSimpleName(), "uid:" + summaryBucket.getUid() + " rx:" + summaryBucket.getRxBytes() +
" tx:" + summaryBucket.getTxBytes()+ "包名 "+ma.getPackageManager().getNameForUid(summaryBucket.getUid()));
summaryTotal += summaryBucket.getRxBytes() + summaryBucket.getTxBytes();
Log.i(MainActivity.class.getSimpleName(), "总的流量:" + summaryTotal/1024/1024 );
} while (summaryStats.hasNextBucket());
}
由于获取的流量是分段的需要自己累加起来就是总的流量使用
网友评论