Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get wifi traffic stats android

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.

like image 657
AlexSC Avatar asked Apr 16 '15 14:04

AlexSC


1 Answers

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!

like image 174
Juan Acevedo Avatar answered Nov 15 '22 00:11

Juan Acevedo