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() }