Youtube usage calculation using TrafficStats

304 views Asked by At

Using TrafficStats i was checking the youtube app data usage.In some devices it is working fine but not with many other devices. I found that from developer site, These statistics may not be available on all platforms. If the statistics are not supported by this device, UNSUPPORTED will be returned.

So in these case how can I get the device app usage ?

I was using TrafficStats.getUidRxBytes(packageInfo.uid) + TrafficStats.getUidTxBytes(packageInfo.uid);

this is returning -1 everytime.

1

There are 1 answers

0
rajeesh On

We can use NetworkStats. https://developer.android.com/reference/android/app/usage/NetworkStats.html Please see a sample repo which I got the clue. https://github.com/RobertZagorski/NetworkStats We can see a similar stackoverflow question as well. Getting mobile data usage history using NetworkStatsManager

Then I needed to modify this logic for some particular devices. In these devices the normal method won't return proper usage values. So I modified is as

/* getting youtube usage for both mobile and wifi. */

    public long getYoutubeTotalusage(Context context) {
            String subId = getSubscriberId(context, ConnectivityManager.TYPE_MOBILE);

//both mobile and wifi usage is calculating. For mobile usage we need subscriberid. For wifi we can give it as empty string value.
            return getYoutubeUsage(ConnectivityManager.TYPE_MOBILE, subId) + getYoutubeUsage(ConnectivityManager.TYPE_WIFI, "");
        }


private long getYoutubeUsage(int networkType, String subScriberId) {
        NetworkStats networkStatsByApp;
        long currentYoutubeUsage = 0L;
        try {
            networkStatsByApp = networkStatsManager.querySummary(networkType, subScriberId, 0, System.currentTimeMillis());
            do {
                NetworkStats.Bucket bucket = new NetworkStats.Bucket();
                networkStatsByApp.getNextBucket(bucket);
                if (bucket.getUid() == packageUid) {
                    //rajeesh : in some devices this is immediately looping twice and the second iteration is returning correct value. So result returning is moved to the end.
                    currentYoutubeUsage = (bucket.getRxBytes() + bucket.getTxBytes());
                }
            } while (networkStatsByApp.hasNextBucket());

        } catch (RemoteException e) {
            e.printStackTrace();
        }

        return currentYoutubeUsage;
    }


    private String getSubscriberId(Context context, int networkType) {
        if (ConnectivityManager.TYPE_MOBILE == networkType) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getSubscriberId();
        }
        return "";
    }