9

我要做的是分别统计3G流量和WiFi流量。现在我知道如何使用 WiFi。以下是 WiFi 的源代码。通过这种方式,我可以计算所有制造商的所有安卓手机的 WiFi 流量。但是我还没有找到3g的类似方法。有人知道吗?

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

2 回答 2

7

从 API 级别 8 (Android 2.2) 开始,有一个类TrafficStats可以提供您需要的内容:

提供网络流量统计的类。这些统计数据包括通过所有接口、通过移动接口以及基于每个 UID 传输和接收的字节数以及传输和接收的网络数据包。

在旧版本上,您可以使用您提到的方法(即读取文件的文件内容/sys/class/net/...)。这篇博文包含TrafficStats方法和文件位置之间的出色映射。这个 SO 帖子包含其作者用来读取这些文件值的源。根据它,您应该首先尝试从“ /sys/class/net/rmnet0/statistics/rx_bytes”文件中读取数字(对于“接收到的字节”值),如果失败,请尝试“ /sys/class/net/ppp0/statistics/rx_bytes”。

于 2011-09-02T12:59:14.457 回答
0

要获取当前的连接类型,您可以使用 TelephonyManager:http: //developer.android.com/reference/android/telephony/TelephonyManager.html

首先检查设备是否连接到默认的移动数据连接,然后检查连接类型:

    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
         }
    }
于 2011-09-02T09:03:21.547 回答