getUidTxBytes(int uid)总是在android 6.0中返回0

Fah*_*aza 7 android android-6.0-marshmallow android-trafficstats

我正在尝试获取所有应用的网络流量统计信息.我只打印设备中每个应用程序的总网络流量.代码在android 4.4和5.1设备中运行良好,但在android 6.0设备中,它总是为所有应用程序返回0.任何人都可以告诉我为什么在Android 6.0设备中发生这种情况.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    for(ApplicationInfo app : getPackageManager().getInstalledApplications(0)){
        long tx = TrafficStats.getUidTxBytes(app.uid);
        long rx = TrafficStats.getUidRxBytes(app.uid);
        long total = tx + rx;
        Log.e("total data of ", app.packageName + " = " + total);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mts.trafficstatsdemo">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
Run Code Online (Sandbox Code Playgroud)

Ole*_*nov 1

根据文档

从 N 开始,这将仅报告呼叫 UID 的流量统计信息。出于隐私原因,对于所有其他 UID,它将返回 UNSUPPORTED。要访问属于其他 UID 的历史网络统计信息,请使用 NetworkStatsManager。