Get wifi traffic stroid android

I am developing an application that allows you to check the statistics of Wi-Fi and mobile traffic on Android. This is how I get statistics:

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

Unfortunately, wifiStats here seems more than Wi-Fi just because even when I turn off Wi-Fi on my smartphone, it gets a lot of data. I think getTotalRxBytes() and getTotalTxBytes() count bytes sent and received on all network interfaces.

I searched on the Internet many times how to get traffic statistics only on Wi-Fi, but I can’t find a way.

I am happy to accept any help.

+5
source share
1 answer

I had the same problem a few years ago, and I solved it by reading 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 this helps!

+6
source

All Articles