Check network connection availability

Updated

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.tanelikorri.android.networkconnection;

import android.app.AlertDialog;
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;

import androidx.appcompat.app.AppCompatActivity;

public class NetworkConnectionActivity extends AppCompatActivity {

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

    public void onCheckNetworkClick(View view) {
        AlertDialog dialog = new Builder(this)
                .setTitle(R.string.app_name)
                .setMessage("Network connection available: " + isNetworkConnectionAvailable())
                .create();

        dialog.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

Did you find this article helpful? Or are there parts that need some improving? Write your comment below and let me know what you think!

comments powered by Disqus