Search code examples
androidandroid-networkingandroid-internet

android how to get indicate when the internet connection is lost?


I'm developing an android application and I want to get a notification when the internet (wifi or packet data connection) connection is lost. On my approach I can get the status of the connection as:

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

while having this in the Manifest:

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

How could I be notified automatically when the connection is lost?


Solution

  • For WIFI you could register a broadcast receiver as:

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    registerReceiver(broadcastReceiver, intentFilter);
    

    You can also register the receiver in the Manifest.

    Then in your receiver:

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
            if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)){
                //do stuff
            } else {
                // wifi connection was lost
            }
        }
    }
    

    For any type of data connection listeners you could use the following receiver registered as:

    <receiver android:name=".receiver.ConnectivityReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>
    

    and the in your ConnectivityReceiver:

    public class ConnectivityReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
        }
    }
    

    In the onReceive method you could check if you have internet connectivity or not using this developer article.