我的 Android 应用(运行 Android 10)使用网络流量统计信息。
当我的设备使用 Wifi 时,TrafficStats.getMobileTxBytes 和 ...getMobileRxBytes 始终返回 0。
当它打开蜂窝网络时,返回的值看起来不错。
有什么想法或解决方案吗?
我的 Android 应用(运行 Android 10)使用网络流量统计信息。
当我的设备使用 Wifi 时,TrafficStats.getMobileTxBytes 和 ...getMobileRxBytes 始终返回 0。
当它打开蜂窝网络时,返回的值看起来不错。
有什么想法或解决方案吗?
您正在使用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()