我正在开发一个Android应用程序,需要检查互联网连接。当设备的WI-FI关闭时,它工作得很好,但是当我打开Wi-Fi但不连接到可用网络时,它是强制关闭。可能是什么问题?请帮忙 bool isNetworkConnectionAvailable() {
boolean connected = false;
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null){
if(ni.isConnected())
connected = true;
else
connected=false;
}
}
return connected;
}
最佳答案
您的问题是,当您的设备连接到 WIFI 时返回 true,但 WIFI 未连接到互联网。您可以通过以编程方式执行 ping 命令来解决此问题。
想法:
1) 检查您是否已连接到 WIFI。
2)如果您连接到 wifi ping 以检查网络可用性。
代码:
public static boolean isOnline(Context con,String url){
ConnectivityManager cm = (ConnectivityManager)con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
if(u!=null){
return ping(url);
}else{
return true;
}
}else{
return false;
}
}
Ping方法:
public static boolean ping(String u) {
try {
URL url = new URL(u);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(500); // Time is in Milliseconds to wait for ping response
urlc.connect();
if (urlc.getResponseCode() == 200) {
Log.i(TAG, "* ping with ResponseCode: "+urlc.getResponseCode());
return true;
}else{
Log.i(TAG, "* Connection is too slow with ResponseCode: "+urlc.getResponseCode());
return false;
}
}catch (MalformedURLException e1){
Log.e(TAG,"Erroe in URL to ping"+e1);
return false;
}catch (IOException e){
Log.e(TAG,"Error in ping"+e);
return false;
}
}
关于android - WI-FI已打开但未连接到网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12257295/