hello,又和大家见面了,刚刚学习的小技巧,来和大家分享!
大家都知道在windows下,如何使用Ping功能,很简单,方便,此处省略200字。。。,回到正题,Android的设备,比如手机,平板等有这个功能吗,答案是有,下面看代码吧,没什么难度,有些地方注意下就可以了。
private boolean pingIpAddr(String ip) { //这里的输入参数是局域网的IP地址 或者 一个网址(设备要可以上网)
String mPingIpAddrResult = "";
try {
String ipAddress = ip;
Process p = Runtime.getRuntime().exec("/system/bin/ping -c " +" 1 "+ ipAddress); // 执行一次
int status = p.waitFor(); //该方法会阻塞,所以要放在线程中执行
if (status == 0) {<span style="white-space:pre"> </span>//表示可以ping通
BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
String str = new String();
int i = 0;
//读出所有信息并显示
while((str = buf.readLine())!=null){ // 获取具体消息
i++;
if(i == 1){
info_header = str + "\r\n";
}
else if(i == 2){
str = str + "\r\n";
info_content = str;
}else{
return true;
}
}
return true;
} else {
mPingIpAddrResult = "Fail: IP addr not reachable";
System.out.println(mPingIpAddrResult);
}
} catch (IOException e) {
mPingIpAddrResult = "Fail: IOException";
e.printStackTrace();
} catch (InterruptedException e) {
mPingIpAddrResult = "Fail: InterruptedException";
e.printStackTrace();
}
return false;
}
其实,就只要这么一个方法就行了,我是在真机做的测试,一点问题都没有,单放在模拟器中,一直Ping不同,知道的给我说一下哈。下面上传下效果图:
我这里做的效果是一秒中,ping一次,仿Windows的啦,具体的就是这样了,知道怎么用就好了,到时候有项目需要,拿来就用,测试代码,我先不上传了,是一个整体的项目包,没有单独项目,想要的猿猿,留邮箱给我就行了。
哈哈,下期再见。