记录: Android测试网速实现

2.3开始android提供了一个流量统计类, android.net.TrafficStats,通过使用这个类提供的方法,就可以获取设备流量。
下面为该类中的常用方法,欢迎大家完善补充

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的发送字节数,某一个进程的总发送量

实现方法

        var TrafficStats;  //TrafficStats类实例对象
        var total_data;    //总共接收到的流量
        var traffic_data;  //一定时间内接收到的流量
        var intervalId;    //定时器的返回值,用于控制计时器的停止
        document.addEventListener('plusready', function(){
            //console.log("所有plus api都应该在此事件发生后调用,否则会出现plus is undefined。"
            TrafficStats = plus.android.importClass("android.net.TrafficStats");
            total_data = TrafficStats.getTotalRxBytes();
            intervalId = window.setInterval("getNetSpeed()", 1000); 
        });

        /**
         * 核心方法
         */
        function getNetSpeed(){
            traffic_data = TrafficStats.getTotalRxBytes() - total_data;
            total_data = TrafficStats.getTotalRxBytes();
            document.getElementById("net").value = bytesToSize(traffic_data);
            console.log(bytesToSize(traffic_data));
        }

        //将byte自动转换为其他单位
        function bytesToSize(bytes) {
            if (bytes === 0) return '0 B/s';
            var k = 1000, // or 1024
                sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
                i = Math.floor(Math.log(bytes) / Math.log(k));
           return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
        }

  原文连接: http://ask.dcloud.net.cn/article/773

https://www.tongbiao.xyz/
原文地址:https://www.cnblogs.com/tongbiao/p/10177398.html