前言
在 Android 开发中合理利用网络不浪费用户流量是每个良心 APP 的目标,收集 APP 的流量使用数据是重要的一环,毕竟没有数据支撑做的优化都是纸上谈兵.一般用户查看流量统计特别都是针对 3G/4G ,会去下载比如 360*** 之类的第三方软件来进行监控,其实 Android 系统提供了一个类给开发者使用,它就是 TrafficStats.
本文的目标是以简单快捷地介绍 TrafficStats 读取本地文件获取应用流量统计的过程,关于其他详细方法和系统服务的相关内容都不做详细解读.
TrafficStats
类注解
/**
* 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.
*
* These statistics may not be available on all platforms. If the statistics are
* not supported by this device, {@link #UNSUPPORTED} will be returned.
*
* Note that the statistics returned by this class reset and start from zero
* after every reboot. To access more robust historical network statistics data,
* use {@link NetworkStatsManager} instead.
*/
TrafficStats 提供网络流量统计.这些统计包括字节的上传/接收和数据包的上传/接收,
流量统计在 Android2.2 之前是不可用的,如果系统版本过低会返回 UNSUPPORTED (-1).
数据统计会在每次手机启动后从零开始算,如果要访问更多详细的网络状态数据就使用 NetworkStatsManager.
TrafficStats 提供的方法有很多,可以通过阅读官方文档了解,我们统计应用流量使用情况通常使用的是 getUidRxBytes().
下面从一个例子开始了解 TrafficStats 如何读取 APP 流量使用情况的,该例子主要通过调用 TrafficStats.getUidRxBytes() 根据应用的 Uid 获取该应用接收字节数.
long uidRxBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid());
while (true) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("uidRxBytes", "当前进程流量:"+ (TrafficStats.getUidRxBytes(
android.os.Process.myUid()) - uidRxBytes));
}
getUidRxBytes()
统计的字节包括 TCP 和 UDP.
// TrafficStats.java
public static long getUidRxBytes(int uid) {
// This isn't actually enforcing any security; it just returns the
// unsupported value. The real filtering is done at the kernel level.
// 获取当前调用所在进程的 UID
final int callingUid = android.os.Process.myUid();
if (callingUid == android.os.Process.SYSTEM_UID || callingUid == uid) {
try {
return getStatsService().getUidStats(uid, TYPE_RX_BYTES);
} catch (RemoteException e) {
throw e