我想要做的是分别计算3G流量和WiFi流量。现在我知道如何处理WiFi。以下是WiFi的源代码。通过这种方式,我可以计算所有制造商的所有Android手机的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";
}
...
...
答案 0 :(得分:7)
从API级别8(Android 2.2)开始,有一个类TrafficStats可提供您所需的内容:
提供网络流量统计信息的类。这些统计数据 包括发送和接收的字节以及传输的网络数据包 并通过所有接口,通过移动界面和a接收 每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
”。
答案 1 :(得分: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
}
}