![](/img/trans.png)
[英]How to check if mobile network is connected to the internet or not in android
[英]android:how to detect network is connected to internet
我有此代碼來檢查互聯網連接。
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))並崩潰。我不知道為什么這段代碼為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.