我有这段代码来检查互联网连接。
NetworkInfo info = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
//if network is active and have internet connection
if(info != null && info.isConnected()==true){
//Some code
}
//if network is inactive or doesn't have internet connection
else if(info == null || info.isConnected()==false){
Context context = getApplicationContext();
CharSequence text = " Bad internet connection.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
当我启动程序时,一切正常,打开互联网连接,但当我从我的路由器拔出网线时,在我的应用程序仍然打开wifi,应用程序实现这个(if(info!= null&& info.isConnected()== true))和crash.I不知道为什么这段代码成真。
答案 0 :(得分:0)
Use this for check condition of network:
if (info!=null && info.isAvailable() && info.isConnected()) {
return true;
} else {
return false;
}
}