Android监听网络下载速度(记录)

一、网络下载速度工具类

/**
 * 网络下载速度工具类
 */
public class DownLoadSpeedUtil {

    public static long lastTotalRxBytes;
    public static long lastTimeStamp;

    /**
     * 获取网络下载速度
     *
     * @param uid
     * @return
     */
    public static int getNetSpeed(int uid) {

        long nowTotalRxBytes = getTotalRxBytes(uid);
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        int result = 0;
        try {
            result = (int) speed;
        } catch (Exception e) {}
        return result;
    }

    public static long getTotalRxBytes(int uid) {
        //转为KB
        return TrafficStats.getUidRxBytes(uid)==TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes()/1024);
    }

    /**
     * 下载速度字符串格式化
     *
     * @param speed
     * @return
     */
    public static String speedFormat(int speed) {
        String result;
        if (speed > 1024) {
            int partA = speed / 1024;
            int partB = (speed - partA * 1024) / 100;
            result = partA + "." + partB + "m/s";
        } else {
            result = speed + "kb/s";
        }
        return result;
    }

}

二、如何使用

(定时服务,然后通过Handler消息机制修改文本显示内容)

private void autoGetDownLoadSpeed() {
    DownLoadSpeedUtil.lastTotalRxBytes = DownLoadSpeedUtil.getTotalRxBytes(getApplicationInfo().uid);
    DownLoadSpeedUtil.lastTimeStamp = System.currentTimeMillis();
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            int speed = DownLoadSpeedUtil.getNetSpeed(getApplicationInfo().uid);
            sendMessage(speed, 0x03, 0);
        }
    }, 1, 100, TimeUnit.MILLISECONDS);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值