你的问题是你返回true当你的遗赠是连接到WIFI,但WIFI不连接到internet.You可以通过执行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;
}
}
什么是例外? – Abhi
我看不到例外,因为无法在模拟器上测试应用程序。 –