[转]Android利用ping方式判定是否连接Internet

2017-03-31  本文已影响0人  扳手扳死你

public classPing {

public static final booleanping() {

String result =null;

try{

String ip ="www.baidu.com";//除非百度挂了,否则用这个应该没问题~

Process p = Runtime.getRuntime().exec("ping -c 2 -w 100 "+ ip);//ping3次

//读取ping的内容,可不加。

InputStream input = p.getInputStream();

BufferedReader in =newBufferedReader(newInputStreamReader(input));

StringBuffer stringBuffer =newStringBuffer();

String content ="";

while((content = in.readLine()) !=null) {

stringBuffer.append(content);

}

LogUtils.i("TTT","result content : "+ stringBuffer.toString());

// PING的状态

intstatus = p.waitFor();

if(status ==0) {

result ="successful~";

return true;

}else{

result ="failed~ cannot reach the IP address";

}

}catch(IOException e) {

result ="failed~ IOException";

}catch(InterruptedException e) {

result ="failed~ InterruptedException";

}finally{

LogUtils.i("TTT","result = "+ result);

}

return false;

}

上一篇下一篇

猜你喜欢

热点阅读