getUidRxBytes() and getUidTxBytes() always return 0 in Andro



我觉得我现在正在服用疯狂的药丸。我的应用程序的某个特定部分已经运行了好几天,今天它刚刚停止运行,我不知道为什么。我的这部分代码用于输出自启动以来每个特定应用程序发送和接收的总数据。现在,这些值总是显示为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)));

更新【2014年1月23日】:在运行Android 4.4.2的Nexus 4上测试getUidRxBytes()和getUidTxBytes(。

我已向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();
}
TrafficStats类从/proc/uid_stat/<uid>目录中获取有关网络流量的信息。其中包含有关发送和接收的tcp、udp字节和数据包的信息。如果文件不存在,TrafficStats类将无法获取网络统计信息。你可以检查文件是否存在,如果没有,你运气不好,应该寻找其他方式。

如果文件存在,你可以试着自己阅读。

此外,getUidTxBytes()和getUIDRxBytes(。因此,如果你的应用程序正在处理大量UDP流量(如voip),那么你将无法获得任何信息。已经为此提交了一个错误:https://code.google.com/p/android/issues/detail?id=32410

我对此做了一些详细的研究,并澄清了一些细节,因为Android 4.3以来,TrafficStats API从设备中提取细节的方式发生了变化。

在Android 4.3之前,UID流量统计可用于TCP和UDP,并包括字节和数据包的API&发送和接收。该数据是从/proc/uid_stat/[pid]/*文件中提取的。

在Android 4.3中,开发人员决定改用更好、更安全的API,使用xt_qtaguid UID统计数据,这是Linux中netfilter内核模块的一部分。此API(procfs)允许基于进程UID进行访问,这就是为什么当您尝试访问Android=>4.3中的TrafficStats API时,您将获得非自有UID的零信息。

顺便说一句,导致问题的提交如下:https://github.com/android/platform_frameworks_base/commit/92be93a94edafb5906e8bc48e6fee9dd07f5049e

*改进TrafficStats UID API。弃用传输层统计信息,只保留摘要网络层统计信息。改进文档以明确测量所在的图层发生,以及它们自启动以来的行为。在发动机罩下,移至使用xt_qtaguid UID统计信息。错误:68186377013662更改Id:I9f26992e5fcdebd88c671e5765bd91229e7b0016*

最新更新