线程获取当前网速的方式

  /** 创建一线程

     * 定义线程周期性地获取网速

     */

    private long old_KB = 0;
    private long new_KB;

 Runnable mRunnable = new Runnable() {
		@Override
		public void run() {
			new_KB = getUidRxBytes() - old_KB;
			old_KB = getUidRxBytes();
			Message msg = new Message();
			msg.what = 0;
			msg.obj = new_KB;
			handler.sendMessage(msg);
			handler.postDelayed(mRunnable, 1000);
		}
	};

old_kb  初始化旧的字节数

new_kb 重新获取总字节数  减去  旧字节数


sdk提供有TrafficStats类的getUidRxBytes,这样方便获取总的接收字节数

包含Mobile 和 WIFI等

代码如下:

/**   获取总字节数

  *  @param    package_name   即当前应用的包名

 */

public long getUidRxBytes() { // 获取总的接受字节数,包含Mobile和WiFi等
		PackageManager pm = getPackageManager();
		ApplicationInfo ai = null;
		try {
			ai = pm.getApplicationInfo("package_name",
					PackageManager.GET_ACTIVITIES);
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}
		return TrafficStats.getUidRxBytes(ai.uid) == TrafficStats.UNSUPPORTED ? 0
				: (TrafficStats.getTotalRxBytes() / 1024);
	}

Handler 实时处理消息数据,更新显示当前接收字节数   Kb/s

Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				long s_KB = (Long) msg.obj;
				mProgressBar.setVisibility(View.VISIBLE);
				mProgressBarTV.setText(s_KB + "kb/s");
				break;
			default:
				break;
			}

		};
	};



你可能感兴趣的:(线程获取当前网速的方式)