我觉得我现在正在疯狂吃药.我的应用程序的一个特定部分已经工作了好几天,今天它只是停止工作,我无法弄清楚为什么.我的代码的这部分用于输出自启动以来每个特定应用程序已发送和接收的总数据.现在,值始终显示为0.
可能会或可能不会影响此事的一些事情:
1.)我的Nexus 4今天刚刚更新到Android 4.3,但我怀疑这是一个问题,因为我在更新后工作得很好.
2.)随着Android API 18更新,流量统计API中的一些方法现在已被弃用,但这些是我甚至不使用的方法,因此这应该没有效果. http://developer.android.com/reference/android/net/TrafficStats.html
非常感谢所有帮助.
PackageManager packageManager=this.getPackageManager();
List<ApplicationInfo> appList=packageManager.getInstalledApplications(0);
for (ApplicationInfo appInfo : appList) {
String appLabel = (String) packageManager.getApplicationLabel(appInfo);
int uid = appInfo.uid;
Log.d("data", String.valueOf(TrafficStats.getUidRxBytes(uid) + TrafficStats.getUidTxBytes(uid)));
Run Code Online (Sandbox Code Playgroud)
更新[2014年1月23日]:在运行Android 4.4.2的Nexus 4上测试getUidRxBytes()和getUidTxBytes()会显示值不再为0,但报告的是正确的统计信息.
我已经向AOSP问题跟踪器报告了这个问题:这里
我还为下面粘贴的问题创建了一个替代解决方案:
private Long getTotalBytesManual(int localUid){
File dir = new File("/proc/uid_stat/");
String[] children = dir.list();
if(!Arrays.asList(children).contains(String.valueOf(localUid))){
return 0L;
}
File uidFileDir = new File("/proc/uid_stat/"+String.valueOf(localUid));
File uidActualFileReceived = new File(uidFileDir,"tcp_rcv");
File uidActualFileSent = new File(uidFileDir,"tcp_snd");
String textReceived = "0";
String textSent = "0";
try {
BufferedReader brReceived = new BufferedReader(new FileReader(uidActualFileReceived));
BufferedReader brSent = new BufferedReader(new FileReader(uidActualFileSent));
String receivedLine;
String sentLine;
if ((receivedLine = brReceived.readLine()) != null) {
textReceived = receivedLine;
}
if ((sentLine = brSent.readLine()) != null) {
textSent = sentLine;
}
}
catch (IOException e) {
}
return Long.valueOf(textReceived).longValue() + Long.valueOf(textReceived).longValue();
}
Run Code Online (Sandbox Code Playgroud)
TrafficStats 类从目录中获取有关网络流量的信息/proc/uid_stat/<uid>。其中包含有关发送和接收的 tcp、udp 字节和数据包的信息。如果文件不存在,TrafficStats 类将无法获取网络统计信息。您可以检查文件是否存在,如果不存在,那么您就不走运,应该寻找其他方法。
如果文件存在,您可以尝试自己阅读。
getUidTxBytes() 和 getUIDRxBytes() 仅报告 TCP 流量并丢失 UDP 流量。因此,如果您的应用程序正在处理大量 UDP 流量(如 voip),那么您将无法获得任何信息。已经为此提交了一个错误:https://code.google.com/p/android/issues/detail?id =32410
| 归档时间: |
|
| 查看次数: |
5857 次 |
| 最近记录: |