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