androidkotlinandroid-trafficstats

TrafficStats.getUidRxBytes return -1


I try get the total Tx and Tr Bytes per installed apps, but always returns -1, except in my app. This is my code:

val pm = context.packageManager
val apps = HashMap<String, Long>()
    for( app in pm.getInstalledApplications(0) ) {
        Log.i(TAG, "app.packageName=${app.packageName} TrafficStats.getUidTxBytes(app.uid)=${TrafficStats.getUidTxBytes(app.uid)} TrafficStats.getUidRxBytes(app.uid)=${TrafficStats.getUidRxBytes(app.uid)}")
        apps.put(app.packageName, TrafficStats.getUidRxBytes(app.uid)+TrafficStats.getUidTxBytes(app.uid))
    }

Solution

  • As per documentation:

    Starting in Build.VERSION_CODES.N this will only report traffic statistics for the calling UID. It will return UNSUPPORTED for all other UIDs for privacy reasons. To access historical network statistics belonging to other UIDs, use NetworkStatsManager.

    When getting return values you don't expect, always check the most recent documentation first.