Runtime runtime = Runtime.getRuntime();
Process process = null;
String line = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
String ip = "www.baidu.com";
boolean res = false;
try
{
//process = runtime.exec("ping " +ip);
process = runtime.exec("ping -c 1 -w 100" +ip);
is = process.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);

while((line = br.readLine()) != null)
{
if(line.contains("TTL"))
{
res = true;
break;
}
}
is.close();
isr.close();
br.close();
if (res)
{
Toast.makeText(MainActivity.this, "ping 成功", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "ping 失败", Toast.LENGTH_SHORT).show();
}
}catch(IOException e)
{
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
runtime.exit(1);
}
在while处,line获取到的值是空的,是我的代码哪里写错了吗?诚求前辈莅临指导

解决方案 »

  1.   

    试试这个
    /**
     * 判断外网是否连接
     * 
     * @param ip
     * @return
     */
    public boolean weatherNetConnect(String ip) { Runtime run = Runtime.getRuntime();
    Process proc = null;
    try {
    String str = "ping -c 1 -i 0.2 -W 1 " + ip;
    System.out.println(str);
    proc = run.exec(str);
    int result = proc.waitFor();
    if (result == 0) {
    return true;
    } else {
    return false;
    }
    } catch (IOException e) {
    e.printStackTrace();
    } catch (InterruptedException e) {
    e.printStackTrace();
    } finally {
    proc.destroy();
    }
    return false;
    }
      

  2.   

    "ping -c 1 -w 100" +ip
    这样100和ip会连在一起的,命令错误
      

  3.   

    /system/bin/ping
      

  4.   


    还是不行.得出else的结果.ping的是百度
      

  5.   

    别沉啊...到底是哪里出了问题不能ping....
      

  6.   


    is 、isr 、br都有值吗?如果也没值,那就检查("ping -c 1 -w 100" +ip) 这里的空格,另外,100太大了吧,如果是写在UI线程,长时间block住会出ANR的问题
      

  7.   


    还是不行.得出else的结果.ping的是百度
    可能系统木有相应的权限