How to detect if user has 3G/Wifi on before making URL connection?
-
02-10-2019 - |
Question
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?
Solution
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);
}
OTHER TIPS
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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow