private long lastTotalRxBytes =
0;
private long lastTimeStamp =
0;
/**
* 得到网络速度
* @param context
* @return
*/
public String
getNetSpeed(Context context) {
String netSpeed =
"0 kb/s";
long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid)==
TrafficStats.UNSUPPORTED ?
0 :(TrafficStats.getTotalRxBytes()/
1024);
long nowTimeStamp = System.currentTimeMillis();
long speed = ((nowTotalRxBytes - lastTotalRxBytes) *
1000 / (nowTimeStamp - lastTimeStamp));
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
netSpeed = String.valueOf(speed) +
" kb/s";
return netSpeed;
}
在我们主线程中每隔两秒调用一次