2012-10-11 60 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

有趣,謝謝你的提示! –

相關問題