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

I'm trying to get а real traffic stats data. But, When i count `TrafficStats.getMobileTxBytes()` for whole day its more than my data pack?

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

TrafficStats.getTotalRxBytes() does not return your data pack value. It refers to the total received bytes (either wifi/mobile) since the last boot (turning ON phone). For mobile data, it will be TrafficStats.getMobileRxBytes()。更重要的是,这些值在每次重新启动设备时都会重置。

I have a 1.5 GB data pack. It gives the total sum of 2.0 GB or more than that .

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

// 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

any idea about how to get correct speed every second.

您无法通过这种方式获得实际速度。您只能计算并显示一秒钟内有多少字节 received/transmitted。我认为 android 中的所有速度计都做同样的事情。类似于以下内容:

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();

虽然这段代码并不完美,但它会满足您的需要。