对于Android流量统计来说在2.2版中新加入了TrafficStats类可以轻松获取,其实本身TrafficStats类也是读取Linux提供的文件对象系统类型的文本进行解析。android.net.TrafficStats类中,提供了多种静态方法,可以直接调用获取,返回类型均为 long型,如果返回等于-1代表 UNSUPPORTED 当前设备不支持统计。
Java代码
static long getMobileRxBytes() static long getMobileRxPackets() static long getMobileTxBytes() static long getMobileTxPackets() static long getTotalRxBytes() static long getTotalRxPackets() static long getTotalTxBytes() static long getTotalTxPackets() static long getUidRxBytes(int uid) static long getUidTxBytes(int uid)
总接受流量TrafficStats.getTotalRxBytes(),
总发送流量TrafficStats.getTotalTxBytes());
不包含WIFI的手机GPRS接收量TrafficStats.getMobileRxBytes());
不包含Wifi的手机GPRS发送量TrafficStats.getMobileTxBytes());
某一个进程的总接收量TrafficStats.getUidRxBytes(Uid));
某一个进程的总发送量TrafficStats.getUidTxBytes(Uid));
这些都是从第一次启动程序到最后一次启动的统计量。并不是
这篇文章里所说的“从本次开机到本次关机的统计量”!
用法举例,注意这里得到的单位都是"KB"
Java代码
public long getTotalRxBytes(){ return TrafficStats.getTotalRxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getTotalRxBytes()/1024); } public long getTotalTxBytes(){ return TrafficStats.getTotalTxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getTotalTxBytes()/1024); } public long getMobileRxBytes(){ return TrafficStats.getMobileRxBytes()==TrafficStats.UNSUPPORTED?0:(TrafficStats.getMobileRxBytes()/1024); }