【发布时间】:2014-08-22 06:25:55
【问题描述】:
我写了一个小安卓应用程序,发送 Http 请求,从服务器接收响应,并计算发送和接收的字节数。 代码如下
long receivedBytes = TrafficStats.getUidRxBytes(uid)-lastNumer
我发现receivedBytes总是比http Header+http Body大,例如 我在服务器中捕获的实际http帧的大小(使用wireshark)是1645字节(header+body),但是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;
}
【问题讨论】: