Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android mobile usage history NetworkStatsManager

I'm making an App for Android 6.0 and I want to use the new class NetworkStatsManager for getting mobile data usage.

I added all permission I need in manifest and require the permission runtime.

When I call the method:

bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_WIFI, "", fromDate.getTime(), toDate.getTime());

return the right value for WIFI usage.

But if i replace TYPE_WIFI with TYPE_MOBILE the result is always 0.

    NetworkStats.Bucket bucket = null;
    try {
        bucket = networkStatsManager.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, "", fromDate.getTime(), toDate.getTime());

        if(bucket == null){
            Log.i("Info", "Error");
        }else{
            Log.i("Info", "Total: " + (bucket.getRxBytes() + bucket.getTxBytes()));
        }

    } catch (RemoteException e) {
        e.printStackTrace();
    }
like image 681
Allen Walker Avatar asked Feb 07 '23 23:02

Allen Walker


1 Answers

I found a solution of this problem with hidden APIs (android statistic 3g traffic for each APP, how?) and when trying to retrieve mobile data usage information with TYPE_MOBILE was necessary to inform the SubscriberID, unlike when I tryed to get information TYPE WIFI.

Try this code

    TelephonyManager  tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
    String subscriberID = tm.getSubscriberId();

    NetworkStats networkStatsByApp = networkStatsManager.queryDetailsForUid(ConnectivityManager.TYPE_MOBILE, subscriberID, start, end, uid);

So when you are using TYPE_MOBILE, it's necessary to you use a valid subscriberID.

like image 136
EMIDIO OLIVEIRA Avatar answered Feb 10 '23 14:02

EMIDIO OLIVEIRA