项目中需要显示当前网络的ping值 那么在android设备上可采取以下方式来获取
m_pingVal 为成员变量
把每次获取到的ping值赋值给该变量即可 由于获取ping值的过程是在子线程中完成
所以主线程的m_pingVal保存的是上一次获取到的ping值
代码如下
// 获取网络延迟(ping)
public static int GetPingValue(String ip, boolean bResetPing) {
if (bResetPing) { m_pingVal = -1; }
try {
// 创建proc子进程去执行ping命令
String tmpStr = "/system/bin/ping -c 4 ";
String cmdStr = tmpStr.concat(ip);
Process proc = Runtime.getRuntime().exec(cmdStr);
// 获取输出流
final InputStream is1 = proc.getInputStream();
// 获取错误流
final InputStream is2 = proc.getErrorStream();
//启动两个线程 一个负责读标准输出流 一个负责读标准错误流
new Thread() {
public void run() {
BufferedReader buf = new BufferedReader(new InputStreamReader(is1));
try {
// 解析输出流
String strRet = null;
while ((strRet = buf.readLine()) != null) {
// 输出示例 xxx rtt min/avg/max/mdev = 15.629/22.753/30.402/6.763
if (strRet.contains("avg")) {
for (int i = 0; i < 6; i++) {
if (i == 4) {
// 22.753/30.402/6.763
//strRet = strRet.substring(0, strRet.indexOf("/"));
m_pingVal = (int)Double.parseDouble(strRet.substring(0, strRet.indexOf("/")));
break;
}
strRet = strRet.substring(strRet.indexOf("/") + 1);
}
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
public void run() {
BufferedReader buf = new BufferedReader(new InputStreamReader(is2));
try {
// 错误信息
String strRet = "";
while ((strRet = buf.readLine()) != null) {
if (strRet != null) {}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// proc.waitFor();
// proc.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return m_pingVal;
}