gpt4 book ai didi

java - Android - 检查互联网访问

转载 作者:行者123 更新时间:2023-11-30 10:45:00 25 4
gpt4 key购买 nike

我已经阅读了这个关于在 Android 中获取互联网连接状态的答案:

https://stackoverflow.com/a/22256277/4225644

但它不能正常工作,例如,如果我有一个没有互联网访问的网络连接,这个方法需要很长时间才能返回 False:

public Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal==0);
return reachable;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}

我怎样才能减少这个时间以获得更快的答案?

最佳答案

使用此代码:

public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo ni = cm.getActiveNetworkInfo();

if (ni == null)
return false;
else {
if (ni.isConnected())
if (isOnline(context))
return true;
else
return false;
return false;
}
}


public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url
.openConnection();
urlc.setConnectTimeout(2000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return new Boolean(true);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}

关于java - Android - 检查互联网访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37226737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com