4

我正在尝试制作一个后台服务,该服务应该测量各种应用程序的流量使用情况,以便能够向用户显示哪些应用程序消耗了最多的数据流量。

我发现 Spare Parts 应用程序正是这样做的,但在 1.6 Dell Streak 设备上安装它后,我总是得到“网络使用情况”的“没有可用的电池使用数据”。这个功能在备件中是否有效?另外,我找不到 Spare Parts 的有效源代码。

https://android.googlesource.com/platform/development/+/froyo-release/apps/SpareParts
看起来已经过时或不完整。(?)

但 Spare Parts 似乎可以衡量每个应用程序的 CPU 使用率。它是如何在无根手机上做到这一点的?

我对如何衡量每个应用程序的流量的总体想法是定期检查

"sys/class/net/" + sWiFiInterface + "/statistics/rx_bytes"

"sys/class/net/" + sWiFiInterface + "/statistics/tx_bytes"

"sys/class/net/" + sMobileInterface + "/statistics/rx_bytes"

"sys/class/net/" + sMobileInterface + "/statistics/tx_bytes"

文件并查看当前哪个应用程序具有焦点,因此最有可能导致生成的网络流量。

不幸的是,我找不到如何让应用程序当前具有焦点。

我找到了这个:

Android,如何获取有关当前正在显示的活动的信息(在前景中)?

但似乎它是关于测试,而不仅仅是在非 root 的 Android 设备上运行的 3d 派对服务。

我们可以获得正在运行的活动ActivityManager.getCurrentTasks(),但其中任何一个都可以成为焦点。出于安全考虑,Android 架构师似乎明确不希望 3d 派对应用程序知道哪些应用程序具有焦点

(见http://android.bigresource.com/Track/android-zb2mhvZX4/)。

有没有解决的办法?

此外,如果我不仅想检测哪些活动占用了流量,还想检测哪些服务,我可以获取所有当前正在运行的服务, ActivityManager.getCurrentSerives() 甚至可以查看每个服务是否处于前台模式(如果 Android 需要资源,则不会被抛出)。但这并没有让我走得更远。

有任何想法吗?

4

1 回答 1

3

You can detect currently foreground application with ActivityManager.getRunningAppProcesses call. It will return a list of RunningAppProcessInfo records. To determine which application is on foreground check RunningAppProcessInfo.importance field for equality to RunningAppProcessInfo.IMPORTANCE_FOREGROUND.

But be ware that call to ActivityManager.getRunningAppProcesses() method must be performed NOT in the UI thread. Just call it in the background thread (for example via AsyncTask) and it will return correct results. Check my post for additional details.

于 2011-03-16T22:26:22.993 回答