Android 网络延迟、丢包率获取

语言: CN / TW / HK

Android获取host访问丢包率和延迟的方法

具体方法

/** * times 次数 * host 访问地址 */ fun netSpeedTest(times: Int, host: String) { Thread { val p = Runtime.getRuntime().exec("ping -c $times $host") val buf = BufferedReader(InputStreamReader(p.inputStream)) var str = "" while (buf.readLine()?.also { str = it } != null) { if (str.contains("packet loss")) { val i = str.indexOf("received") val j = str.indexOf("%") val lost = str.substring(i + 10, j + 1) Log.i(TAG, "丢包率:$lost") } if (str.contains("avg")) { val i = str.indexOf("/", 20) val j = str.indexOf(".", i) val delay = str.substring(i + 1, j) Log.i(TAG, "平均延迟:$delay ms") } } }.start() }