2012-10-11 29 views
2

有没有一种方法来统计在Android中通过WiFi/LAN使用和传输的数据?我可以通过TrafficStats方法getMobileTxBytes()getMobileRxBytes()查看移动互联网(3G,4G)的统计数据,但WiFi的情况如何?如何统计通过WiFi/LAN发送和接收的字节数?

+0

看到这个http://stackoverflow.com/q/8478696/1321873? – Rajesh

回答

1

更新:下面的原始答案很可能是错误。我得到的WiFi/LAN的数字太高了。还没有想通为什么(似乎测量流量通过WiFi/LAN是不可能的),而是一个老问题提供了一些启示:How to get the correct number of bytes sent and received in TrafficStats?


找到我自己的答案。

首先,定义一个名为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; 
} 

接下来,定义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); 
} 

1

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

+0

有趣,谢谢你的提示! –

相关问题