Android获取网速的方法

xiaoxiao2021-02-27  567

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; }

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

转载请注明原文地址: https://www.6miu.com/read-1704.html

最新回复(0)