I'm comparing the new NetworkStats
class with TrafficStats
for measuring traffic for the network interfaces and a given application (pex Chrome)
Since TrafficStats
has values since device boot the test that I'm performing is this:
- Reboot phone.
- Open Chrome.
- Download 10 mb data (over WiFi).
The data obtained with TrafficStats
is this:
TrafficStats.getTotalRxBytes() aprox 17.21 MB
TrafficStats.getUidRxBytes(chromeUid) aprox 13.22 MB
I grant the permission to NetworkStats
and the values that I obtain are this:
wifiBucket.getRxBytes() + mobileBucket.getRxBytes() aprox 17.23 MB
dataFromWiFiBucket[1] + dataFromMobileBucket[1] gives 0 bytes
The code to obtain the data from NetworkStats
is the following:
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);
Where getDataFromBucket
is:
@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};
}
I've read somewhere that buckets are from two hours so I've added this code:
if (bootTime > (timeStamp - TimeUnit.HOURS.toMillis(TWO_HOURS))) {
bootTime = timeStamp - TimeUnit.HOURS.toMillis(TWO_HOURS);
}
But data for chrome is still 0 because wifiBucketForApp
and mobileBucketForApp
do not have any buckets.
If I set bootTime
to the beginning of the day (its 18:30 in my country) I obtain:
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
Does anybody know why I'm not obtaining the same values as TrafficStats
since device boot from NetworkStatsManager
for the Chrome app?
Since it's not your own app's traffic you need to allow manually Usage data access in the device settings.