【问题标题】:how to count 3g traffic in android mobile?如何统计安卓手机的3g流量?
【发布时间】:2011-11-09 00:18:15
【问题描述】:

我要做的是分别统计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";
}
...
...

【问题讨论】:

    标签: android network-traffic


    【解决方案1】:

    要获取当前的连接类型,您可以使用 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
             }
        }
    

    【讨论】:

    • 作者问的是如何统计3G流量,而不是如何判断当前的连接类型
    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多