Find how much network traffic other Android apps generate

こ雲淡風輕ζ 提交于 2019-12-01 04:48:56

问题


I am trying to make a background service which should measure traffic usage of various applications so as to be able to show to the user which apps consume most data traffic.

I found that Spare Parts app does exactly that, but after installing it on a 1.6 Dell Streak device I always get "No battery usage data available" for "Network usage". Does this function at all work in Spare Parts? Also, I couldn't find a working source code for Spare Parts.

https://android.googlesource.com/platform/development/+/froyo-release/apps/SpareParts
looks to be outdated or incomplete. (?)

But Spare Parts seems to measure e.g. CPU usage per app. How does it do that on an unrooted phone?

My general idea of how traffic per app could be measured is to regularly check the

"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"

files and to see which app currently has focus and thus most likely to cause the generated network traffic.

Unfortunately I can't find how to get the app currently having focus.

I found this:

Android, how to get information on which activity is currently showing (in foregorund)?

but seems it's about testing, not just a 3d party service running on non-rooted Android device.

We can get what activities are running with ActivityManager.getCurrentTasks(), but any of them can be the one with focus. It seems like the Android architects explicitly don't want 3d party apps to know what app has focus, because of security concerns

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

Is there a way around this?

Also, if I want to not only detect which activities eat up traffic but also what services, I can get all currently running services with ActivityManager.getCurrentSerives() and even see for each one if it's in foreground mode (unlike to be thrown out if Android needs resources). But this again doesn't bring me any far.

Any ideas?


回答1:


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.



来源:https://stackoverflow.com/questions/5327985/find-how-much-network-traffic-other-android-apps-generate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!