android 检测网速


package com.egreat.onekeyapk.util;

import java.util.Timer;
import java.util.TimerTask;

import com.egreat.onekeyapk.ui.MainActivity;
import com.egreat.onekeyapk.ui.MyDialog;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.TrafficStats;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class NetSpeed {
	private final static String TAG	 = "NetSpeed";
	private long preRxBytes = 0;
	private Timer mTimer = null;
	private Context mContext;
	private static NetSpeed mNetSpeed;
	private Handler mHandler;
	private MyDialog mMyDialog;

	private NetSpeed(Context mContext,Handler mHandler){
		this.mContext = mContext;
		this.mHandler = mHandler;
	}
	
	public static NetSpeed getInstant(Context mContext,Handler mHandler){
		if(mNetSpeed == null){
			mNetSpeed = new NetSpeed(mContext,mHandler);
		}
		return mNetSpeed;
	}
	
	private long getNetworkRxBytes() {
		int currentUid = getUid();
		Log.d(TAG, "currentUid ="+currentUid);
		if (currentUid < 0) {			
			return 0;
		}
		long rxBytes = TrafficStats.getUidRxBytes(currentUid);
		/*下句中if里的一般都为真,只能得到全部的网速*/
		if (rxBytes == TrafficStats.UNSUPPORTED) {
			Log.d(TAG, "getUidRxBytes fail !!!");/*本函数可以只用下面一句即可*/
			rxBytes = TrafficStats.getTotalRxBytes();
		}
		return rxBytes;
	}
	public int getNetSpeed() {

		long curRxBytes = getNetworkRxBytes();
		long bytes = curRxBytes - preRxBytes;
		preRxBytes = curRxBytes;
		int kb = (int) Math.floor(bytes / 1024 + 0.5);
		return kb;
	}

	public void startCalculateNetSpeed() {
		preRxBytes = getNetworkRxBytes();
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimer == null) {
			mTimer = new Timer();
			mTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					Message msg = new Message();
					msg.what = Constants.HandlerMsg.UPDATENETSPEED;
					msg.arg1 = getNetSpeed();
					mHandler.sendMessage(msg);
				}
			}, 1000, 1000);
		}
	}

	public void stopCalculateNetSpeed() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}
	/*下面这个函数可以不用*/
	private int getUid() {
		try {
			PackageManager pm = mContext.getPackageManager();
			ApplicationInfo ai = pm.getApplicationInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
			return ai.uid;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return -1;
	}

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值