androidandroid-6.0-marshmallowandroid-trafficstatsnetworkstatsmanager

NetworkStatsManager's queryDetailsForUid() method always returns old network usage for all the apps


I have written a code to get network usage but queryDetailsForUid(int networkType, String subscriberId,long startTime, long endTime, int uid) this method always returns old data. How can I get updated data using NetworkstatsManager API?

    try {
            NetworkStats  networkStats = networkStatsManager.queryDetailsForUid(
                            ConnectivityManager.TYPE_WIFI,
                            "",
                    0, System.currentTimeMillis()
                    ,
                    packageUid);

            NetworkStats.Bucket bucket = new NetworkStats.Bucket();
            networkStats.getNextBucket(bucket);
            Log.d("RX  "+packageUid," "+bucket.getRxBytes());
            Log.d("TX  "+packageUid," "+bucket.getTxBytes());

    } catch(Exception e){

    }

Solution

  • I used the same method, It does not return old data. You can test the date and time of your bucket using :

    Log.d(TAG,"StartTime: "+bucket.getStartTimeStamp());
    Log.d(TAG,"EndTime: "+bucket.getEndTimeStamp());
    

    Check the end Timestamp , you shud see current date and time. AFAIK, each bucket is of 2 hrs.

    Whole Code:

                do {
                NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                networkStatsByApp.getNextBucket(bucket);
                Log.d(TAG, "Bytes Recieved" + bucket.getRxBytes());
                Log.d(TAG, "Bytes Transfered" + bucket.getTxBytes());
                Log.d(TAG, "Bucket UID" + bucket.getUid());
                Log.d(TAG,"StartTime: "+bucket.getStartTimeStamp());
                Log.d(TAG,"EndTime: "+bucket.getEndTimeStamp());
                totalBuckets++;
    
            }while (networkStatsByApp.hasNextBucket());