I don't want my app to crash if the user doesn't have wifi or 3g connectivity. How can I catch this at runtime in my app?
First get a reference to the ConnectivityManager and then check the Wifi and 3G status of the device. You'll need the ACCESS_NETWORK_STATE permission to use this service.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mWifi.isConnected() == false && mMobile.isConnected() == false) {
showDialog(DIALOG_NETWORK_UNAVAILABLE);
}
connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) is deprecated.
Below is an improved solution for the latest Android SDK.
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
boolean is3gEnabled = false;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connManager.getAllNetworks();
for(Network network: networks)
{
NetworkInfo info = connManager.getNetworkInfo(network);
if(info!=null) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
is3gEnabled = true;
break;
}
}
}
}
else
{
NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(mMobile!=null)
is3gEnabled = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With