TrafficStats.getUidRxBytes return -1

TrafficStats.getUidRxBytes return -1

我尝试获取每个已安装应用程序的总 Tx 和 Tr 字节数,但总是 returns -1,我的应用程序除外。这是我的代码:

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))
    }

根据文档:

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.

当获得 return 出乎意料的值时,请始终先检查最新的文档。