Search code examples
javaandroidandroid-wifi

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?


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);
        }