androidandroid-trafficstats

How to monitor other apps network usage?


I use TrafficStats.getUidRxBytes to get network usage. It works fine for my app but for other apps always returns -1 (UNSUPPORTED). How can i get network usage for other apps without root permission?


Solution

  • Since android 7, you can query only your own app traffic usage. From TraffixStats.getUidRxBytes docs:

    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.

    Going to NetworkStatsManager, you could use queryDetailsForUid, but as documentation (https://developer.android.com/reference/android/app/usage/NetworkStatsManager.html) says:

    NOTE: Calling querySummaryForDevice(int, String, long, long) or accessing stats for apps other than the calling app requires the permission PACKAGE_USAGE_STATS, which is a system-level permission and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application.

    So be warned that the user must give some special permission to your app.

    Edit:

    I used once UsageStatsManager, I think it's what you are looking for: https://developer.android.com/reference/android/app/usage/UsageStatsManager.html#queryUsageStats(int,%20long,%20long)