问题:(注:因为设备和测试环境等因素的不同,问题并不是一定会出现)
1、短时间执行ping命令,如果不加入waitFor,可能BufferedReader还未读取到信息代码就跑完了,这种情况下得不到执行结果。
2、加入waitFor后,长时间执行ping命令,有可能会因为waitFor的长时间等待而不能正常读取数据。
解决:
在读取前后都加入waitFor,并做时间判断。
代码:
private Process p;
private void pingNet(long times){
try {
String line;
String pingPath = "www.baidu.com";
String pingCmd = "ping -i 1 -c " + times + " " + pingPath;
p = Runtime.getRuntime().exec(pingCmd);
// 仅用于短时间内的测试,如果长时间测试,会因为waitFor的长时间等待而不能正常读取到数据,因此长时间测试时waitFor用于读取数据之后
if (times < 10){
p.waitFor(times+10,TimeUnit.SECONDS);//测试总时间上加入10s的等待时间,避免阻塞
}
{
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int receivedCount = 0;//接收的数据包
int transmittedCount = 0; // 发送的数据包
Log.e(TAG, "in.readLine() = " + in.readLine());
while ((line = in.readLine()) != null) {
Log.e(TAG, "line : " + line);
if (line.contains("received")) { //检查line字符串包含“received”的行
// 解析输出行,提取接收到的数据包数量
// "if pass line = " 10 packets transmitted, 10 received, 0% packet loss, time 9013ms
String[] parts = line.split(","); //将line字符串按照 , 分割成多个部分,并将这些部分存储在数组中
transmittedCount = Integer.parseInt(parts[0].trim().split(" ")[0]); //移除parts[0]字符串两端的空白字符,按空格分割,并取出第一个部分转换为整数
receivedCount = Integer.parseInt(parts[1].trim().split(" ")[0]); //移除parts[1]字符串两端的空白字符,按空格分割,并取出第一个部分转换为整数
}
}
in.close();
NET_PASS = String.valueOf(receivedCount);
NET_TOTAL = String.valueOf(transmittedCount);
}
Log.e(TAG, "waitFor....");
boolean status = p.waitFor(10,TimeUnit.SECONDS);//加入10s的等待时间,避免阻塞
if (!status ){
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer stringBufferErr=new StringBuffer();
String errorLine;
while ((errorLine = err.readLine()) != null) {
stringBufferErr.append(errorLine+"\n");
}
Log.e(TAG, "getErrorStream输出信息为"+ stringBufferErr +" 长度为"+stringBufferErr.length());
err.close();
NET_PASS = String.valueOf(stringBufferErr);
NET_TOTAL = "FAIL";
}
} catch (Exception e) {
Log.e(TAG," "+e.getMessage());
}
}
我翻看了这部分的源码,利用提供的函数换了几种解决方案,并未找出更好的解决方法,如果有朋友有更好的解决方案,可以在评论区探讨一下,欢迎大家评论和质疑😄
文章讨论了在执行ping命令时如何避免因等待时间过长导致数据读取问题,提出在读取前后加入waitFor并进行时间判断的解决方案,同时鼓励读者分享更优解。
2115





