简体   繁体   中英

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

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 (ie 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.

to get the current type of connection you can use the TelephonyManager: http://developer.android.com/reference/android/telephony/TelephonyManager.html

first check if the device is connected to the default mobile data connection and then check the connection type:

    if (connectinTpe == ConnectivityManager.TYPE_MOBILE)
    {
         TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
         int curConnectionType = tm.getNetworkType();

         if(curConnectionType >= /*connection type you are looking for*/)
         {
             // do what you want
         }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM