android trafficstats,简单了解 Android 流量统计之 TrafficStats

本文介绍了Android系统提供的TrafficStats类,用于获取应用的流量使用数据。 TrafficStats提供了网络流量统计,包括字节和数据包的上传/接收,并在每次重启后重置。文章详细解析了TrafficStats的getUidRxBytes()方法,通过调用系统服务获取应用接收字节数。同时,还探讨了TrafficStats如何通过AIDL与NetworkStatsService交互,并深入到C++层的实现细节,涉及BPF流量监控和/proc/net/xt_qtaguid/stats文件的解析。
摘要由CSDN通过智能技术生成

前言

在 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值