Using BroadcastReceiver to check network connectivity in Android

A BroadcastReceier in Android can be registered to receive system events. In the following example, we are going to register a BroadcastReceiver to receive actions when the network connectivity is changed.

1. Create a class which extends from BroadcastReceiver. The important part here for receiving the intent is in the onReceive method. The other methods are for checking the network connectivity. Turn on or off the airplane mode to trigger this broadcast event of CONNECTIVITY_ACTION.

public class ConnectivityChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        final String action = intent.getAction();
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            checkConnectivity(context);
        }
    }


    private void checkConnectivity(final Context context) {
        if (!isNetworkInterfaceAvailable(context)) {
            Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
            return;
        }

        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final boolean isConnected = isAbleToConnect("http://www.google.com", 1000);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (isConnected)
                            Toast.makeText(context, "You are ONLINE!", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(context, "You are OFFLINE!", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        }).start();

    }

    //This only checks if the network interface is available, doesn't guarantee a particular network service is available, for example, there could be low signal or server downtime
    private boolean isNetworkInterfaceAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    //This makes a real connection to an url and checks if you can connect to this url, this needs to be wrapped in a background thread
    private boolean isAbleToConnect(String url, int timeout) {
        try {
            URL myUrl = new URL(url);
            URLConnection connection = myUrl.openConnection();
            connection.setConnectTimeout(timeout);
            connection.connect();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

2. Register the receiver in the application tag of the manifest file to receive the CONNECTIVITY_CHANGE intent.

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

Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search