Android网络测速
2019-07-15 本文已影响0人
主音King
Android 8.1系统新增网络测速功能
自动对附近的WiFi进行测速测试,如果附近的无线网络处于加密状态,Google无权也无法对其进行测速
以4个等级进行评价
慢(Slow):0-1Mbps,可以使用 WLAN 通话功能、接打电话和收发短信
良好(Ok):1-5Mbps,可以浏览网页、使用社交媒体软件以及听音乐
快速(Fast):5-20Mbps,可以观看大部分视频
非常快(Very Fast):20Mbps以上,可以观看非常高质量的视频
利用Trafficstats流量测速度:上行、下行
private static long lastTotalRxBytes = 0;
private static long lastTotalTxBytes = 0;
private static long lastTimeStamp = 0;
public static String getNetSpeed(int uid) {
long nowTotalRxBytes = getTotalRxBytes(uid);
long nowTotalTxBytes = getTotalTxBytes(uid);
long nowTimeStamp = System.currentTimeMillis();
Log.d(TAG, "网络-x----速度-nowTotalTxBytes:" + nowTotalTxBytes+" 时间:"+(nowTimeStamp - lastTimeStamp) +"差量:"+(nowTotalTxBytes - lastTotalTxBytes)+" nowTotalTxBytes:"+nowTotalTxBytes+" lastTotalTxBytes:"+lastTotalTxBytes);
long speedRx = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
long speedTx = ((nowTotalTxBytes - lastTotalTxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换
lastTimeStamp = nowTimeStamp;
lastTotalRxBytes = nowTotalRxBytes;
lastTotalTxBytes = nowTotalTxBytes;
Log.d(TAG, "网络-x-速度下行:" + (speedRx + " kB/s") + " 上行:" + speedTx + " kB/s");
return speedRx + " kB/s";
}
/**
* 下行 700kB/s 直播临界
* 实际用到的流量
* @param uid getApplicationInfo().uid 当前线程
* @return
*/
public static long getTotalRxBytes(int uid) {
return TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
}
/**
* 上行实际用到的流量
* @param uid getApplicationInfo().uid 当前线程
* @return
*/
public static long getTotalTxBytes(int uid) {
return TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalTxBytes() / 1024);//转为KB
}
在Android 4.3上,速度为0问题:可以用以下方法获取
private Long getTotalBytesManual(int localUid){
File dir = new File("/proc/uid_stat/");
String[] children = dir.list();
if(!Arrays.asList(children).contains(String.valueOf(localUid))){
return 0L;
}
File uidFileDir = new File("/proc/uid_stat/"+String.valueOf(localUid));
File uidActualFileReceived = new File(uidFileDir,"tcp_rcv");
File uidActualFileSent = new File(uidFileDir,"tcp_snd");
String textReceived = "0";
String textSent = "0";
try {
BufferedReader brReceived = new BufferedReader(new FileReader(uidActualFileReceived));
BufferedReader brSent = new BufferedReader(new FileReader(uidActualFileSent));
String receivedLine;
String sentLine;
if ((receivedLine = brReceived.readLine()) != null) {
textReceived = receivedLine;
}
if ((sentLine = brSent.readLine()) != null) {
textSent = sentLine;
}
}
catch (IOException e) {
}
return Long.valueOf(textReceived).longValue() + Long.valueOf(textSent).longValue();
}