- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我写了一个小的 android 应用程序,发送 Http 请求,从服务器接收响应,并计算传输和接收的字节数。代码如下
long receivedBytes = TrafficStats.getUidRxBytes(uid)-lastNumer
我发现 receivedBytes 总是大于 http Header+http Body 的大小,例如我在服务器中捕获(使用 wireshark)的实际 http 帧大小为 1645 字节( header +正文),但 android API 返回 receivedBytes 为 1912,因此传输。
TrafficStats getUidRxBytes 本身不准确(可能这个问题是我的平台 samsung i9300 和 cynogenmod 10.3 特有的)
最后,我找到了计算数据使用量的正确方法我找到了其他方法来计算数据使用量,这似乎比 TrafficStats API 更准确。(非常感谢 here)
private long[] getStat() {
String line, line2;
long[] stats = new long[2];
try {
File fileSnd = new File("/proc/uid_stat/"+uid+"/tcp_snd");
File fileRcv = new File ("/proc/uid_stat/"+uid+"/tcp_rcv");
BufferedReader br1 = new BufferedReader(new FileReader(fileSnd));
BufferedReader br2 = new BufferedReader(new FileReader(fileRcv));
while ((line = br1.readLine()) != null&& (line2 = br2.readLine()) != null) {
stats[0] = Long.parseLong(line);
stats[1] = Long.parseLong(line2);
}
br1.close();
br2.close();
} catch (Exception e) {
e.printStackTrace();
}
return stats;
}
最佳答案
我看到您已经找到了解决方案,但我会在您的问题上添加我的想法,因为它可能对其他人有用(在谷歌搜索如何使用 TrafficStats API 后,我自己最终来到这里)。
Statistics are measured at the network layer, so they include both TCP and UDP usage.
文档确实可以更详尽,但我倾向于说可以假设返回的字节数还包括构成传输层 header 和网络层 header 的字节。
HTTP is an application layer protocol .当您将预期字节计算为 HTTP header 字节加上 HTTP 正文字节时,您只处理应用程序层字节,因此不考虑传输层和网络层 header 字节。我假设 TCP 用于下载。 This adds a header ranging from 20 to 60 bytes .此外,假设您使用 IPv4 进行下载。 This also adds a header ranging from 20 to 60 bytes .
显然这不会占整个 1912 - 1645 = 267 字节,但它可能会给你/其他人一些线索。
有点离题,但还是相关的。目前尚不清楚 TrafficStats API 是否实际计算 header 字节数。根据this answer , API 不计算 header 字节。但是,考虑到上面列出的 API 文档,链接的答案可能规定了不正确的内容(至少对于 API 级别 21 而言并非如此)。此外,this question还暗示 TrafficStats 实际上在计算网络和传输层 header 字节(查看评论)。
TrafficStats 实际上计算网络和传输层 header 字节。参见 kernel source和 TrafficStatsTest .
关于android TrafficStats getUidRxBytes 不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25440796/
我写了一个小的 android 应用程序,发送 Http 请求,从服务器接收响应,并计算传输和接收的字节数。代码如下 long receivedBytes = TrafficStats.getUidR
我制作了这个程序,我的 TrafficStats.getUidRxBytes() 方法一直给我 0。我检查了我的应用程序并有数据使用记录,但我的代码没有显示接收和发送数据量的数据使用量。另外,当我打印
我正在尝试弄清楚如何检索按应用分割的单独移动(蜂窝/3G/4G)数据使用情况和单独的 WIFI 使用情况。我看到 android.trafficstats 有 getUidRxBytes/getUid
我觉得我现在正在服用疯狂的药丸。我的应用程序的特定部分几天来一直运行良好,今天它停止工作,我不明白为什么。我的这部分代码用于输出自启动以来每个特定应用程序已发送和接收的总数据。现在,值始终显示为 0。
我是一名优秀的程序员,十分优秀!