Android TrafficStats - 超大价值是一个错误?

时间:2013-12-12 21:08:59

标签: android traffic-measurement

我正在调查android中的流量测量。我正在开发Galaxy S4,我编写了一个每分钟捕获一次TrafficStats API的服务,在SharedPreference中保存累积流量(AKA BaseTraffic)并在数据库中保存当前流量减去BaseTraffic之间的差异。

问题在于,在短时间内(15分钟),TrafficStats会返回一个超大值(每分钟1.6 GB)和相同的值。有人知道这是一个错误还是其他问题。

excel dump

我的代码是获取流量的下一个代码:

public class TrafficTracker {

    public static long getCurrentTraffic() {
        long traff = 0;
        traff = (TrafficStats.getTotalRxBytes() + TrafficStats.getTotalTxBytes());
        if (traff > 0) {
            return traff;
        } else {
            throw new UnsupportedOperationException("TrafficStats not supported");
        }

    }

    public static long getTrafficWithOutBase(long baseTraffic) {
        return TrafficStats.getTotalTxBytes() + TrafficStats.getTotalRxBytes() - baseTraffic;
    }
}

在此处调用此代码:

if (preferences.getBaseTraffic() != null) {
    if (TrafficTracker.getCurrentTraffic() > preferences.getBaseTraffic().getByteTraffic()) {

        TrafficObject trafficObject = new TrafficObject(new Date(calendar.getTimeInMillis()), TrafficTracker.getTrafficWithOutBase(preferences.getBaseTraffic().getByteTraffic()));
        daoTraffic.create(trafficObject);

        preferences.setBaseTraffic(new TrafficObject(new Date(System.currentTimeMillis()), preferences.getBaseTraffic().getByteTraffic() + trafficObject.getByteTraffic()));

    } else {//when stats are reseted            
        TrafficObject trafficObject = new TrafficObject(new Date(calendar.getTimeInMillis()), TrafficTracker.getCurrentTraffic());
        daoTraffic.create(trafficObject);
        preferences.setBaseTraffic(trafficObject);          
    }

}

**更新**

我发现了我的错误:)。我替换了> =而不是>。现在,当它与数据或wifi断开连接时,它可以正常工作。

    if (TrafficTracker.getCurrentTraffic() >= preferences.getBaseTraffic().getByteTraffic())

1 个答案:

答案 0 :(得分:0)

我发现了我的错误:)。我替换了> =而不是>。现在,当它与数据或wifi断开连接时,它可以正常工作。

    if (TrafficTracker.getCurrentTraffic() >= preferences.getBaseTraffic().getByteTraffic())