Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if user has 3G/Wifi on before making URL connection?

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?

like image 975
Sheehan Alam Avatar asked Sep 09 '10 21:09

Sheehan Alam


2 Answers

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);
    }
like image 147
Jason Knight Avatar answered Oct 30 '22 06:10

Jason Knight


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;
        }
like image 36
Krzysztof Huminski Avatar answered Oct 30 '22 06:10

Krzysztof Huminski