如何在 Android 中 ping 一些 Web 服务器以测试我是否有 Internet 连接?所以我需要 ping 给定站点的方法,如果我没有 Internet,则返回 false,如果有,则返回 true。
问问题
24405 次
2 回答
11
请参阅此方法,这是检查与给定服务器的连接性的最佳方法:
http://developer.android.com/reference/java/net/InetAddress.html#isReachable(int)
于 2013-07-05T16:12:21.043 回答
0
使用这些方法 ping 服务器
public static void inSomeWhere()
{
String pingResult = getPingResult("168.126.63.1");
boolean isNetOk = true;
if (pingResult == null) {
// not reachable!!!!!
isNetOk = false;
}
}
public static String getPingResult(String a) {
String str = "";
String result = "";
BufferedReader reader = null;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
try {
Runtime r = Runtime.getRuntime();
Process process = r.exec("/system/bin/ping -c 3 " + a);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
int i;
while ((i = reader.read(buffer)) > 0)
output.append(buffer, 0, i);
str = output.toString();
final String[] b = str.split("---");
final String[] c = b[2].split("rtt");
if (b.length == 0 || c.length == 0)
return null;
if(b.length == 1 || c.length == 1)
return null;
result = b[1].substring(1, b[1].length()) + c[0] + c[1].substring(1, c[1].length());
} catch (IOException e) {
return null;
} catch (Exception e) {
return null;
}
finally
{
if(reader != null)
{
try{reader.close();}catch(IOException ie){}
}
}
return result;
}
于 2018-05-18T06:35:40.753 回答