GetUidTxBytes (int uid) always returns 0 in android 6.0

I am trying to get network traffic statistics for all applications. I just print the total network traffic of each application on my device. The code works fine on android 4.4 and 5.1 devices, but on android 6.0 it always returns 0 for all applications. Anyone can tell me why this happened on 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 is 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> 
+7
android android-6.0-marshmallow
source share
2 answers

According to doc :

Starting with N, only traffic statistics for the calling UID will be displayed. It will return UNSUPPORTED for all other UIDs for privacy reasons. To access historical network statistics belonging to a different UID, use NetworkStatsManager.

+1
source share

Try to get the data of the current application, and, surprisingly, you will notice that you can really get network information for your own application, the reason is listed below:

Prior to Android 4.3, UID traffic statistics were available for TCP and UDP and included APIs for bytes and packets, and were also sent and received. This data was extracted from the files / proc / uid _stat / [pid] / *.

In Android 4.3, the developers decided to switch to a better and more secure API using the UID xt_qtaguid statistics, which is part of the Linux netfilter kernel module. This API (procfs) allows you to access based on the UID of the process, and that is why when you try to access the TrafficStats API in Android => 4.3, you will get zero information for a non-native UID.

Thus, the current way to handle the problem may be as follows:

1) NetworkStatsManager: This involves using permission at the system level. 2) Manually read the files / proc / uid _stat /

Please note that in a later version, data is cleared at boot.

Thanks.

-one
source share

All Articles