我正在调查android中的流量测量。我正在 Galaxy S4 上开发,我编写了一个服务,该服务每分钟捕获一次 TrafficStats API,将累积流量(AKA BaseTraffic)保存在 SharedPreference 中,并将当前流量减去 BaseTraffic 之间的差值保存在数据库中。
问题在于,在短时间内(15 分钟),TrafficStats 返回一个过大的值(每分钟 1.6 GB)并且永远是相同的值。有人知道这是错误还是其他问题。
我的代码是获取流量的下一个代码:
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())