Check network connection availability

As Android is mostly used in mobile devices, it’s useful to know the current state of the network connection. For example if no connection is available the application can show an information dialog to the user explaining the situation.

Basics

The following Activity checks for a connection using the ConnectivityManager class. It first queries the NetworkInfo instance and then ask the state from that instance.

To check the connection state the application needs to have the ACCESS_NETWORK_STATE permission.

Example

package com.caphal.android.networkconnection;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;

public class NetworkConnectionActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network_connection);
    }

    public void onCheckNetworkClick(View view) {
        Builder builder = new Builder(this);

        builder.setTitle(R.string.app_name);
        builder.setMessage("Network connection available: " + isNetworkConnectionAvailable());

        builder.create().show();
    }

    private boolean isNetworkConnectionAvailable() {

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo currentNetwork = cm.getActiveNetworkInfo();

        // Return the value of isConnected if the network connection is
        // available
        if (currentNetwork != null) {
            return currentNetwork.isConnected();
        }

        // Otherwise return false
        return false;
    }
}

Screenshots

Network connection available No connection

Source code

Source code for the whole example project is available here

Further reading

Comments

comments powered by Disqus