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

Android 如何计算通过WiFi/LAN发送和接收的字节数?,android,network-traffic,Android,Network Traffic,有没有办法统计Android中通过WiFi/LAN消耗和传输的数据?我可以通过TrafficStats方法getMobileTxBytes()和getMobileRxBytes()检查移动互联网(3G、4G)的统计数据,但是WiFi呢?更新:下面的原始答案很可能是错误的。我得到的WiFi/LAN的数字太高了。仍然没有弄清楚原因(似乎无法通过WiFi/LAN测量流量),但一个老问题提供了一些见解: 找到了我自己的答案 首先,定义一个名为getNetworkInterface()的方法。我不知道“

有没有办法统计Android中通过WiFi/LAN消耗和传输的数据?我可以通过
TrafficStats
方法
getMobileTxBytes()
getMobileRxBytes()
检查移动互联网(3G、4G)的统计数据,但是WiFi呢?

更新:下面的原始答案很可能是错误的。我得到的WiFi/LAN的数字太高了。仍然没有弄清楚原因(似乎无法通过WiFi/LAN测量流量),但一个老问题提供了一些见解:


找到了我自己的答案

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

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;
}
最后,构建返回通过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);
}
(这实际上是对你答案的评论,没有足够的分数来真正评论,但…)
TrafficStats。不受支持的
不一定意味着设备不支持读取WiFi流量统计数据。以我的三星Galaxy S2为例,当禁用WiFi时,包含统计信息的文件不存在,但在启用WiFi时它可以工作。

看到了吗?如果您在手机上使用代理(例如shadowsocks),当它运行时,它与WiFi和移动接口一起被视为一个单独的网络接口,奇怪的是,在我的测试中,这个差异是巨大的!
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);
}