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);//转为KB;
long nowTimeStamp = System.currentTimeMillis();
long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
netSpeed = String.valueOf(speed) + " kb/s";
return netSpeed;
}
在我们主线程中每隔两秒调用一次
本文介绍了一种通过Java代码实现的网络速度监测方法,利用TrafficStats获取应用接收的字节数,并通过时间间隔计算出实时网速,适用于Android平台。
7543

被折叠的 条评论
为什么被折叠?



