[英]android:how to detect network is connected to internet
I have this code to check for internet connection. 我有此代码来检查互联网连接。
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();
}
When I start the program,everything works properly with turn on internet connection,but when I pull out the internet cable from my router and in my app still have turn on wifi the app get true with this (if(info != null && info.isConnected()==true)) and crash.I don't know why this code get true. 当我启动程序时,打开互联网连接一切正常,但是当我从路由器拔出互联网电缆,并且在我的应用程序中仍然打开wifi时,应用程序就可以做到这一点(if(info!= null && info .isConnected()== true))并崩溃。我不知道为什么这段代码为true。
Use this for check condition of network:
if (info!=null && info.isAvailable() && info.isConnected()) {
return true;
} else {
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.