android中,获取网速的方法实现

 

 private long lastTotalRxBytes = 0;
 private long lastTimeStamp = 0;

 

 /**
     * 得到网络速度
     * @param context
     * @return
     */
    public String getNetSpeed(Context context) {
        String netSpeed = "0 kb/s";
        long nowTotalRxBytes = TrafficStats.getUidRxBytes(context.getApplicationInfo().uid)==TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB;
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;
        netSpeed  = String.valueOf(speed) + " kb/s";
        return  netSpeed;
    }

 

 

   在我们主线程中每隔两秒调用一次

 

posted @ 2017-04-21 17:34  chengxu虾  阅读(908)  评论(0编辑  收藏  举报