我正在比较新的NetworkStats类和TrafficStats来测量网络接口和给定应用程序的流量(pex )
由于TrafficStats具有自设备启动以来的值,所以我正在执行的测试如下:
使用TrafficStats获得的数据如下:
TrafficStats.getTotalRxBytes() aprox 17.21 MB
TrafficStats.getUidRxBytes(chromeUid) aprox 13.22 MB我将权限授予NetworkStats,所获得的值如下:
wifiBucket.getRxBytes() + mobileBucket.getRxBytes() aprox 17.23 MB
dataFromWiFiBucket[1] + dataFromMobileBucket[1] gives 0 bytes从NetworkStats获取数据的代码如下:
long timeStamp = System.currentTimeMillis();
long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
NetworkStats.Bucket wifiBucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI, null, bootTime, timeStamp);
NetworkStats.Bucket mobileBucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, subscriberID, bootTime, timeStamp);
NetworkStats wifiBucketForApp = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_WIFI, null, bootTime, timeStamp, chromeUid);
NetworkStats mobileBucketForApp = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_MOBILE, subscriberID, bootTime, timeStamp, chromeUid);
long[] dataFromWiFiBucket = getDataFromBucket(wifiBucketForApp);
long[] dataFromMobileBucket = getDataFromBucket(mobileBucketForApp);其中getDataFromBucket是:
@RequiresApi(api = Build.VERSION_CODES.M) public static long[] getDataFromBucket(NetworkStats bucketForApp) {
long dataTx = 0;
long dataRx = 0;
NetworkStats.Bucket bucket;
while (bucketForApp.hasNextBucket()) {
bucket = new NetworkStats.Bucket();
bucketForApp.getNextBucket(bucket);
dataTx += bucket.getTxBytes();
dataRx += bucket.getRxBytes();
}
return new long[]{dataTx, dataRx};
}我在某个地方读到桶是从两个小时开始的,所以我添加了以下代码:
if (bootTime > (timeStamp - TimeUnit.HOURS.toMillis(TWO_HOURS))) {
bootTime = timeStamp - TimeUnit.HOURS.toMillis(TWO_HOURS);
}但是chrome的数据仍然是0,因为wifiBucketForApp和mobileBucketForApp没有任何存储桶。
如果我将bootTime设置为一天的开始(在我的国家为18:30 ),我将获得:
wifiBucket.getRxBytes() + mobileBucket.getRxBytes() aprox 44.74 MB (expected because is since the beginning of the day)
dataFromWiFiBucket[1] + dataFromMobileBucket[1] gives 26.32 MB有谁知道为什么我没有获得与TrafficStats相同的值,因为设备从NetworkStatsManager引导Chrome应用程序?
发布于 2019-09-17 15:19:03
由于它不是您自己的应用程序的流量,所以您需要在设备设置中允许手动使用数据访问。
https://stackoverflow.com/questions/41105451
复制相似问题