TrafficStats 网络实时测速

<span style="font-size:48px;">android 2.2版本以上,监听网络实时下载KB速度</span>
<span style="font-size:48px;">定义:</span>
<pre name="code" class="java">private long lastTotalRxBytes = 0;
private long lastTimeStamp = 0;

 
 
private void showNetSpeed() {
		 
	    long nowTotalRxBytes = getTotalRxBytes();
	    long nowTimeStamp = System.currentTimeMillis();
	    long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
	 
	    lastTimeStamp = nowTimeStamp;
	    lastTotalRxBytes = nowTotalRxBytes;
	     
//	    Message msg = mHandler.obtainMessage();
//	    msg.what = 100;
//	    msg.obj = String.valueOf(speed) + " kb/s";
//	     
//	    mHandler.sendMessage(msg);//更新界面
	    Log.e("当前网速为:", String.valueOf(speed) + " kb/s" );
	}
	

	 
	private long getTotalRxBytes() {
	    return TrafficStats.getUidRxBytes(getApplicationInfo().uid)==TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB
	}
	
 
 
<span style="font-size:48px;">调用:</span>
 
 
 
 

/************************网络实时测速*******TrafficStats******************************/
		
		TimerTask task = new TimerTask() {
		    @Override
		    public void run() {
		        showNetSpeed();
		    }
		};
		
		lastTotalRxBytes = getTotalRxBytes();
		lastTimeStamp = System.currentTimeMillis();
		new Timer().schedule(task, 1000, 2000); // 1s后启动任务,每2s执行一次
/*******************************************************************************/




你可能感兴趣的:(TrafficStats 网络实时测速)