如何计算通过WiFi/LAN发送和接收的字节数



在安卓系统中,有没有办法统计通过WiFi/LAN消耗和传输的数据?我可以通过TrafficStats方法getMobileTxBytes()getMobileRxBytes()查看移动互联网(3G、4G)的统计数据,但WiFi如何?

(这实际上是对你的答案的评论,还没有足够的分数来真正评论…)TrafficStats.UNSUPPORTED并不一定意味着设备不支持读取WiFi流量统计数据。在我的三星Galaxy S2的情况下,当WiFi被禁用时,包含统计数据的文件不存在,但当WiFi被启用时,它可以工作。

更新:下面的原始答案很可能是错误。我得到的WiFi/LAN的数字太高了。仍然没有弄清楚为什么(似乎不可能通过WiFi/LAN测量流量),但一个老问题提供了一些见解:如何获得TrafficStats中发送和接收的正确字节数?


找到了自己的答案。

首先,定义一个名为getNetworkInterface()的方法。我不知道"网络接口"到底是什么,但我们需要它返回的String令牌来构建包含字节计数的文件的路径。

private String getNetworkInterface() {
String wifiInterface = null;
try {
Class<?> system = Class.forName("android.os.SystemProperties");
Method getter = system.getMethod("get", String.class);
wifiInterface = (String) getter.invoke(null, "wifi.interface");
} catch (Exception e) {
e.printStackTrace();
}
if (wifiInterface == null || wifiInterface.length() == 0) {
wifiInterface = "eth0";
}
return wifiInterface;
}

接下来,定义readLongFromFile()。实际上,我们将有两个文件路径——一个用于发送的字节,另一个用于接收的字节。此方法只是封装读取提供给它的文件路径,并将计数返回为长。

private long readLongFromFile(String filename) {
RandomAccessFile f = null;
try {
f = new RandomAccessFile(filename, "r");
String contents = f.readLine();
if (contents != null && contents.length() > 0) {
return Long.parseLong(contents);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (f != null) try { f.close(); } catch (Exception e) { e.printStackTrace(); }
}
return TrafficStats.UNSUPPORTED;
}

最后,构建返回通过WiFi/LAN发送和接收的字节数的方法。

private long getNetworkTxBytes() {
String txFile = "sys/class/net/" + this.getNetworkInterface() + "/statistics/tx_bytes";
return readLongFromFile(txFile);
}
private long getNetworkRxBytes() {
String rxFile = "sys/class/net/" + this.getNetworkInterface() + "/statistics/rx_bytes";
return readLongFromFile(rxFile);
}

现在,我们可以通过做一些类似上面移动互联网的例子来测试我们的方法。

long received = this.getNetworkRxBytes();
long sent = this.getNetworkTxBytes();
if (received == TrafficStats.UNSUPPORTED) {
Log.d("test", "TrafficStats is not supported in this device.");
} else {
Log.d("test", "bytes received via WiFi/LAN: " + received);
Log.d("test", "bytes sent via WiFi/LAN: " + sent);
}

最新更新