【问题标题】:Bad value returned by TrafficStatsTrafficStats 返回的错误值
【发布时间】:2020-02-24 16:49:32
【问题描述】:
我的 Android 应用(运行 Android 10)使用网络流量统计信息。
当我的设备使用 Wifi 时,TrafficStats.getMobileTxBytes 和 ...getMobileRxBytes 总是返回 0。
当它打开蜂窝网络时,返回值看起来不错。
有什么想法或解决方案吗?
【问题讨论】:
标签:
android
android-wifi
android-networking
cellular-network
android-trafficstats
【解决方案1】:
你正在使用TrafficStats.getMobileTxByte
来自文档:
返回自设备以来通过移动网络传输的字节数
开机。计算所有移动网络接口上的数据包,并且始终
自设备启动以来单调增加。统计量是在
网络层,因此它们包括 TCP 和 UDP 的使用。
如你所说:
总是返回 0。当它打开蜂窝网络时,返回的值看起来不错。
是的,这是因为当蜂窝网络关闭时,不使用移动(蜂窝)数据,因此为 0。
您可以使用它来获取整个设备使用的数据:
val totalBytes = TrafficStats.getTotalRxBytes()
如果您想获得非蜂窝流量,可以使用以下方法:
val nonMobileBytes = TrafficStats.getTotalRxBytes() - TrafficStats.getMobileTxBytes
https://developer.android.com/reference/android/net/TrafficStats#getTotalRxBytes()