Search code examples
androidnetworkstatsmanager

NetworkStatsManager.queryDetailsForUid is not getting proper data for given time Interval


1) I am checking on Nougat, I already have following permission

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission
android:name="android.permission.PACKAGE_USAGE_STATS"
tools:ignore="ProtectedPermissions"/>

2) Code Snipet

    public long getPackageRxBytesWifi() {
    NetworkStats networkStats = null;
    NetworkStats.Bucket bucket;
    long totalData= 0;
    try {
        networkStats = networkStatsManager.queryDetailsForUid(
                ConnectivityManager.TYPE_WIFI,
                "",
                1488441600 ,
                1488902400 ,
                packageUid);
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    do {
        bucket = new NetworkStats.Bucket();
        networkStats.getNextBucket(bucket);
        Log.i("abc", "Start Time Stamp: " + bucket.getStartTimeStamp());
        Log.i("abc", "End Time Stamp: " + bucket.getEndTimeStamp());
        totalData= totalData+ bucket.getRxBytes() + bucket.getTxBytes();
    }while (networkStats.hasNextBucket());
    return totalData;

3) When I gives interval Start Time - 0 End Time - System.currentTimeMillis(), getting proper data. But when I gives other time interval Start Time - 1488441600 (2 march) End Time - 1488902400 (7 march 11;30) Above method is returning 0. And bucket.getEndTimeStamp() and bucket.getStartTimeStamp() getting printed in Log as 0. Anyone know how to get data from above query for specific time interval Please correct me where I am doing wrong.


Solution

  • It looks to me like you are actually passing in seconds when it should be in milliseconds. Below I've converted your times to milliseconds. Could you try adjusting your code to the following?

    try {
            networkStats = networkStatsManager.queryDetailsForUid(
                    ConnectivityManager.TYPE_WIFI,
                    "",
                    1488441600000L ,
                    1488902400000L ,
                    packageUid);
        } catch (RemoteException e) {
            e.printStackTrace();
    }