80,476
社区成员
发帖
与我相关
我的任务
分享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);
}
2楼说的空格的问题,楼主有无检查
试试这个 /** * 判断外网是否连接 * * @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; }