我正在尝试获取真实的流量统计数据。但是,当我一整天计算"TrafficStats.getMobileTxBytes()"时,它比我的数据包还要多?



例如。我有一个1.5 GB的数据包。它提供了2.0 GB或更多的总和。关于如何获得正确的每秒速度的任何想法。

TrafficStats.getTotalRxBytes()不会返回数据包值。它是指自上次启动(打开手机(以来接收的总字节数(wifi/移动(。对于移动数据,它将是TrafficStats.getMobileRxBytes()。更重要的是,这些值会在每次重新启动设备时重置。

我有一个1.5 GB的数据包。它提供2.0 GB或更多的总容量除此之外。

android系统对您的数据包一无所知。您正在一次又一次地添加它。当您在某个时刻调用TrafficStats.getMobileRxBytes()时,它会返回自上次启动以来到该时刻接收的移动数据总数。以下是解释。希望这能有所帮助。

// Suppose, you have just rebooted your device, then received 400 bytes and transmitted 300 bytes of mobile data
// After reboot, so far 'totalReceiveCount' bytes have been received by your device over mobile data.
// After reboot, so far 'totalTransmitCount' bytes have been sent from your device over mobile data.
// Hence after reboot, so far 'totalDataUsed' bytes used actually.
long totalReceiveCount = TrafficStats.getMobileRxBytes();
long totalTransmitCount = TrafficStats.getMobileTxBytes();
long totalDataUsed = totalReceiveCount + totalTransmitCount;
Log.d("Data Used", "" + totalDataUsed + " bytes"); // This will log 700 bytes
// After sometime passed, another 200 bytes have been transmitted from your device over mobile data.
totalDataUsed = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
Log.d("Data Used", "" + totalDataUsed + " bytes"); // Now this will log 900 bytes

关于如何获得每秒正确速度的任何想法。

您无法通过这种方式获得实际速度。您只能计算和显示一秒钟内接收/传输了多少字节。我认为安卓系统中所有的速度计都是一样的。类似以下内容:

class SpeedMeter {
private long uptoNow = 0;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private ScheduledFuture futureHandle;
public void startMeter() {
final Runnable meter = new Runnable() {
public void run() {
long now = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
System.out.println("Speed=" + (now - uptoNow)); // Prints value for current second
uptoNow = now;
}
};
uptoNow = TrafficStats.getMobileRxBytes() + TrafficStats.getMobileTxBytes();
futureHandle = scheduler.scheduleAtFixedRate(meter, 1, 1, SECONDS);
}
public void stopMeter() {
futureHandle.cancel(true);
}
}

像这样使用:

SpeedMeter meter = new SpeedMeter();
meter.startMeter();

尽管此代码并不完美,但它将适合您的需求。

相关内容

  • 没有找到相关文章

最新更新