Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count 3g traffic in android mobile?

What I want to do is to count 3G traffic and WiFi traffic respectively. Now I know how to do with WiFi. Below is the source code for WiFi. By this way I can count WiFi traffic for all the android phones of all manufactures. But I haven't found a similar way for 3g. Does anyone know?

//to get wifi interface  
private static String getProp(String prop){
    String output = "";
    try{
        Class<?> sp = Class.forName("android.os.SystemProperites");
        Method get = sp.getMethod("get",String.class);
        output = (String)get.invoke(null,prop);
    }catch(Exception e){
        e.printStackTrace();
    }
    return output;
}


//to get the traffic from system file
...
...
if (connectinTpe == ConnectivityManager.TYPE_WIFI){
    String wifiInterface = getProp("wifi.interface");
    if(wifiInterface == null || "".equals(wifiInterface)) wifiInterface = "eth0";
    rxFile = "/sys/class/net/" +wifiInterface+ "/statistics/rx_bytes";
    txFile = "/sys/class/net/" +wifiInterface+ "/statistics/tx_bytes";
}
...
...
like image 916
user924829 Avatar asked Sep 02 '11 08:09

user924829


1 Answers

Starting from API level 8 (Android 2.2) there is a class TrafficStats which provides what you need:

Class that provides network traffic statistics. These statistics include bytes transmitted and received and network packets transmitted and received, over all interfaces, over the mobile interface, and on a per-UID basis.

On the older versions you can use the approach you mentioned (i.e. reading file content of /sys/class/net/... files). This blog post contains an excellent mapping between TrafficStats methods and file locations. And this SO post contains the source its author used to read those files values. According to it you should first try to read number from "/sys/class/net/rmnet0/statistics/rx_bytes" file (for "received bytes" value) and if it fails try "/sys/class/net/ppp0/statistics/rx_bytes" instead.

like image 100
Idolon Avatar answered Sep 30 '22 23:09

Idolon