TrafficStats API's getMobileRxBytes() and getMobileTxBytes() not working properly

299 views Asked by At

The issue is known: when wifi is up, TrafficStats.getMobileRxBytes() and getMobileTxBytes() return 0 since Lollipop (https://issuetracker.google.com/issues/37009612). I found a workaround ignoring zero values, except that on some devices (e.g Samsung 5G), when on wifi,  we get non-0 values. It brings only rmnet1 interface value traffic (rmnet1 is for VoLTE, rmnet0 for normal data).

1/ why only on Samsung devices? while it seems to be handled by Android OS

2/ another observation still on Samsung 5G devices (at least on Samsung S20): when wifi is down, cell counter (all cell traffic since boot: rmnet0 + rmnet1) is inconsistent, sometime we get a value V1, sometime a value V2 (different from V1)

A similar experience?

1

There are 1 answers

4
akshay choukimath On

I haven't used 5G enabled devices, but as of i know, using NetworkStats.Bucket's object we can query for RxBytes and TxBytes with the help of querySummaryForDevice() which takes around 4 parameters

  1. Connectivity(Mobile data, WIFI)
  2. SubscriberID(here for OS 10+ we need to pass null and for previous versions we need to pass subscriber id using TELEPHONY_SERVICE).
  3. Starttime
  4. Endtime.

you can get subscriberID using below code

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

This worked for me to get the RxBytes and TxBytes.