'Get data usage for Wi-Fi and cellular network in Android java for Android versions above pie

I would like to know how to determine the data usage for the specific application above Android version pie programmatically. I found from Android 10 onwards subscriber Id is not accessible to third party applications. Hence I'm not able to fetch data usage using networkStatsManager. But I found there are applications in Play store which provide the solution . I would like to know the implementation for the same.



Solution 1:[1]

I'm not sure on this but they actually use the /proc/net/dev file generated by the phone to get the data .

An example to do that without permissions would be to use a function like this

public static long[] getNetworkUsageKb() {
    BufferedReader reader;
    String line;
    String[] values;
    long[] totalBytes = new long[2];//rx,tx
    try {
        reader = new BufferedReader(new FileReader("/proc/net/dev"));

        while ((line = reader.readLine()) != null) {
            if (line.contains("eth") || line.contains("wlan")){
                values = line.trim().split("\\s+");
                totalBytes[0] +=Long.parseLong(values[1]);//rx
                totalBytes[1] +=Long.parseLong(values[9]);//tx
            }
        }
        reader.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    //transfer to kb
    totalBytes[0] =  totalBytes[0] / 1024;
    totalBytes[1] =  totalBytes[1] / 1024;

    return totalBytes;
}

SO Question on data in proc-net-dev

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Narendra_Nath