Android network delay, packet loss rate acquisition

Method for Android to obtain host access packet loss rate and delay

specific method

/**
 * 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()
}
复制代码

Guess you like

Origin juejin.im/post/7158772682496933919