Get wifi traffic stats android

▼魔方 西西 提交于 2019-12-01 03:09:00

问题


I am developping an app which allows to check wifi and mobile traffic stats on android. That's how I get the stats :

long mobileStats = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
long wifiStats = TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes() - mobileStats;

Unfortunately, wifiStats here seems to be more than wifi only because even when i disable wifi on my smartphone, it gets me tons of data. I think that getTotalRxBytes() and getTotalTxBytes() are counting bytes transmitted and received on all Network Interfaces.

I searched a lot on the web how to get traffic stats only on wifi but i cannot find a way.

I would gladly accept any help.


回答1:


I had the same problem a few years back and solved this by reading the system files directly.

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;
}

Hope it helps!



来源:https://stackoverflow.com/questions/29677403/get-wifi-traffic-stats-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!