I am comparing the new NetworkStats class with TrafficStats for measuring traffic for network interfaces and this application (pex Chrome)
Since TrafficStats matters, since the device is loading the test that I am running, it is:
- Reboot the phone.
- Open Chrome.
- Download 10 MB of data (via WiFi).
The data obtained using TrafficStats is as follows:
TrafficStats.getTotalRxBytes() aprox 17.21 MB TrafficStats.getUidRxBytes(chromeUid) aprox 13.22 MB
I grant NetworkStats permission, and the values I get are as follows:
wifiBucket.getRxBytes() + mobileBucket.getRxBytes() aprox 17.23 MB dataFromWiFiBucket[1] + dataFromMobileBucket[1] gives 0 bytes
The code for retrieving data from NetworkStats as follows:
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 :
@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 read somewhere that buckets are from two hours, so I added this code:
if (bootTime > (timeStamp - TimeUnit.HOURS.toMillis(TWO_HOURS))) { bootTime = timeStamp - TimeUnit.HOURS.toMillis(TWO_HOURS); }
But the data for chrome is still 0, because wifiBucketForApp and mobileBucketForApp do not have any buckets.
If I set bootTime at the beginning of the day (its 18:30 in my country), I get:
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 anyone know why I am not getting the same values as TrafficStats , since loading a device from NetworkStatsManager for a Chrome application?