我正在尝试计算移动数据使用量,所以我使用广播通知我有关3G连接,然后我运行Service
来计数数据。
问题是计算值总是小于Android数据使用默认应用程序计算的值。
代码如下:
long now = TrafficStats.getMobileRxBytes();
long before = now;
do {
now = TrafficStats.getMobileRxBytes() ;
Diffnow = now - before;
SystemClock.sleep(500);
}while ((cm.getActiveNetworkInfo() != null) && (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE));
Log.i(TAG,"delta = "+(float)Diffnow/(1024*1024));
我想我找到了答案为了计算数据使用量,我们必须计算发送和接收的数据,因此我必须更改代码如下:
long now = TrafficStats.getMobileRxBytes()+TrafficStats.getMobileTxBytes();
long before = now;
long Diffnow ;
do {
now = TrafficStats.getMobileRxBytes()+TrafficStats.getMobileTxBytes() ;
Diffnow = now - before;
SystemClock.sleep(500);
}while ((cm.getActiveNetworkInfo() != null) && (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE));
Log.i(TAG,"delta = "+(float)Diffnow/(1024*1024));