我正在开发一个应用程序,它允许在 android 上检查 wifi 和移动流量统计信息。这就是我获得统计数据的方式:
long mobileStats = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
long wifiStats = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes() - mobileStats;
不幸的是,wifiStats
似乎不仅仅是 wifi,因为即使我在智能手机上禁用 wifi,它也会为我提供大量数据。
我认为 getTotalRxBytes()
和 getTotalTxBytes()
正在计算所有网络接口(interface)上传输和接收的字节数。
我在网上搜索了很多如何仅在 wifi 上获取流量统计信息,但找不到方法。
我很乐意接受任何帮助。
最佳答案
几年前我遇到过同样的问题,通过直接读取系统文件解决了这个问题。
private final String RX_FILE = "/sys/class/net/wlan0/statistics/rx_bytes";
private final String TX_FILE = "/sys/class/net/wlan0/statistics/tx_bytes";
private long readFile(String fileName){
File file = new File(fileName);
BufferedReader br = null;
long bytes = 0;
try{
br = new BufferedReader(new FileReader(file));
String line = "";
line = br.readLine();
bytes = Long.parseLong(line);
} catch (Exception e){
e.printStackTrace();
return 0;
} finally{
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
希望对您有所帮助!
关于java - 获取 wifi 流量统计 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677403/