问题
I am trying to get network traffic stats of all apps. I just print total network traffic of every application in my device. The code is working fine in android 4.4 and 5.1 devices but in android 6.0 device it always return 0 for all applications. Anyone can please tell me why this happened in android 6.0 devices.
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);
}
}
Here's my 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>
回答1:
According to doc:
Starting in 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.
回答2:
Try to get the data of the current app and surprisingly you will notice that you can actually get the network details for the own app, the reason is stated below:
Prior to Android 4.3 the UID traffic stats were available for TCP and UDP and included API for bytes and packets & sent and received. That data was extracted from the /proc/uid_stat/[pid]/* files.
In Android 4.3, the developers has decided to switch to a better and more safe API, using the xt_qtaguid UID statistics, which is part of the netfilter kernel module in Linux. This API (procfs) allows access based on process UID, and this is why when you try to access to TrafficStats API in Android=>4.3 you will get zero information for not-own UID.
So the current way of handling the issue can be :
1) NetworkStatsManager : This involves using a system level permission. 2) Manually Read the files /proc/uid_stat/
Note that in the later option the data gets cleared off on boot.
Thanks.
来源:https://stackoverflow.com/questions/41406551/getuidtxbytesint-uid-always-return-0-in-android-6-0