如何监控其他应用程序网络使用情况?

How to monitor other apps network usage?

我使用 TrafficStats.getUidRxBytes 来获取网络使用情况。它适用于我的应用程序但对于其他应用程序始终 returns -1(不支持)。如何在没有root权限的情况下获取其他应用程序的网络使用情况?

从android7开始,您只能查询自己的应用流量使用情况。来自 TraffixStats.getUidRxBytes 文档:

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.

转到 NetworkStatsManager,您可以使用 queryDetailsForUid,但正如文档 (https://developer.android.com/reference/android/app/usage/NetworkStatsManager.html) 所说:

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.

因此请注意,用户必须对您的应用授予一些特殊权限。

编辑:

我用过一次UsageStatsManager,我想这就是你要找的:https://developer.android.com/reference/android/app/usage/UsageStatsManager.html#queryUsageStats(int,%20long,%20long)