android 實時獲取網速


public class NetSpeed {
    private static final String TAG = NetSpeed.class.getSimpleName();
    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;
 
    public String getNetSpeed(int uid) {
        long nowTotalRxBytes = getTotalRxBytes(uid);
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒轉換
        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;
        return String.valueOf(speed) + " kb/s";
    }
 
 
    //getApplicationInfo().uid
    public long getTotalRxBytes(int uid) {
        return TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//轉為KB
    }

  

public class NetSpeedTimer {
    private long defaultDelay = 1000;
    private long defaultPeriod = 1000;
    private static final int ERROR_CODE = -101011010;
    private int mMsgWhat = ERROR_CODE;
    private NetSpeed mNetSpeed;
    private Handler mHandler;
    private Context mContext;
    private SpeedTimerTask mSpeedTimerTask;
 
    public static final int NET_SPEED_TIMER_DEFAULT = 101010;
 
    public NetSpeedTimer(Context context, NetSpeed netSpeed, Handler handler) {
        this.mContext = context;
        this.mNetSpeed = netSpeed;
        this.mHandler = handler;
    }
 
    public NetSpeedTimer setDelayTime(long delay) {
        this.defaultDelay = delay;
        return this;
    }
 
    public NetSpeedTimer setPeriodTime(long period) {
        this.defaultPeriod = period;
        return this;
    }
 
    public NetSpeedTimer setHanderWhat(int what) {
        this.mMsgWhat = what;
        return this;
    }
 
    /**
     * 開啟獲取網速定時器
     */
    public void startSpeedTimer() {
        Timer timer = new Timer();
        mSpeedTimerTask = new SpeedTimerTask(mContext, mNetSpeed, mHandler,
                mMsgWhat);
        timer.schedule(mSpeedTimerTask, defaultDelay, defaultPeriod);
    }
 
    /**
     * 關閉定時器
     */
    public void stopSpeedTimer() {
        if (null != mSpeedTimerTask) {
            mSpeedTimerTask.cancel();
        }
    }
 
    /**
     * @author
     * 靜態內部類
     */
    private static class SpeedTimerTask extends TimerTask {
        private int mMsgWhat;
        private NetSpeed mNetSpeed;
        private Handler mHandler;
        private Context mContext;
 
        public SpeedTimerTask(Context context, NetSpeed netSpeed,
                              Handler handler, int what) {
            this.mContext = context;
            this.mHandler = handler;
            this.mNetSpeed = netSpeed;
            this.mMsgWhat = what;
        }
 
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (null != mNetSpeed && null != mHandler) {
                Message obtainMessage = mHandler.obtainMessage();
                if (mMsgWhat != ERROR_CODE) {
                    obtainMessage.what = mMsgWhat;
                } else {
                    obtainMessage.what = NET_SPEED_TIMER_DEFAULT;
                }
                obtainMessage.obj = mNetSpeed.getNetSpeed(mContext
                        .getApplicationInfo().uid);
                mHandler.sendMessage(obtainMessage);
            }
        }
    }
}
 

  調用:

private void initNewWork() {
        //創建NetSpeedTimer實例
        mNetSpeedTimer = new NetSpeedTimer(mContext, new NetSpeed(), mHandler).setDelayTime(1000).setPeriodTime(2000);
        //在想要開始執行的地方調用該段代碼
        mNetSpeedTimer.startSpeedTimer();
    }
 
 
 private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == NetSpeedTimer.NET_SPEED_TIMER_DEFAULT){
                String speed = (String) msg.obj;
                //打印你所需要的網速值,單位默認為kb/s
                Log.i(TAG, "current net speed  = " + speed);
            }
        }
    };


@Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if(null != mNetSpeedTimer){
            mNetSpeedTimer.stopSpeedTimer();
        }
        super.onDestroy();
    }

  

2.3開始android就提供來這個類的API,這樣我們就可以方便的用他來實現統計手機流量來。這個類其實也很簡單,貼上他的幾個方法,大家一看就知道怎么用了。

static long getMobileRxBytes() //獲取通過Mobile連接收到的字節總數,不包含WiFi
static long getMobileRxPackets() //獲取Mobile連接收到的數據包總數
static long getMobileTxBytes() //Mobile發送的總字節數
static long getMobileTxPackets() //Mobile發送的總數據包數
static long getTotalRxBytes() //獲取總的接受字節數,包含Mobile和WiFi等
static long getTotalRxPackets() //總的接受數據包數,包含Mobile和WiFi等
static long getTotalTxBytes() //總的發送字節數,包含Mobile和WiFi等
static long getTotalTxPackets() //發送的總數據包數,包含Mobile和WiFi等
static long getUidRxBytes(int uid) //獲取某個網絡UID的接受字節數,某一個進程的總接收量
static long getUidTxBytes(int uid) //獲取某個網絡UID的發送字節數,某一個進程的總發送量

 

參考於:https://blog.csdn.net/always_and_forever_/article/details/81974920

參考:

https://www.csdn.net/gather_27/MtTakg1sNzQ3MC1ibG9n.html

https://www.jianshu.com/p/377ffb0f24ad

https://blog.csdn.net/xueshao110/article/details/82766390

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM