Search code examples
androidandroid-wifi

Can android differentiate between a lost internet connection and no internet connect?


When I press a button on my app to open an image it shows a progress bar of the image being downloaded and then it opens. If there is no wifi connection it displays an error message saying "No wifi". I have used the code below to check for a wifi connection:

        ConnectivityManager cm =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork.isConnectedOrConnecting();
        boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

I want to implement an error message that is displayed when the connection is lost. So if you click on the image and while its downloading you turn off the wifi then it displays a message saying "wifi disconnected".

Is this possible? Whether a connection is lost or there is no wifi all you are doing is checking if there is a connection available which is the same thing


Solution

  • You need to use a BroadcastReceiver that will be triggered when the connectivity status for Wi-Fi has changed.

    Set following things before registering BroadcastReceiver:

    private class ConnectionChangeReceiver extends BroadcastReceiver {
    public void onReceive( Context context, Intent intent ) {
    Log.d(tag, "Inside Broadcast Reciever");
    CheckWifiStatus();
    }
    }
    
    private void RegisterWifiWatcher()
    {
    if(wifiWatcher == null)
    wifiWatcher = new ConnectionChangeReceiver();
    
        final IntentFilter intentFilter= new IntentFilter();
        intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        intentFilter.addAction("android.net.wifi.STATE_CHANGE");    
        registerReceiver(wifiWatcher, intentFilter);
    }
    

    WIFI_STATE_CHANGED :

    Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.

    Permissions in Manifest :

    <user-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <user-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    

    NOTE: The broadcast intents that we receive for the different WiFi states have extras along with them that you can access to determine the different states of the WiFi connection.