Get network status in Android studio using Java

In this tutorial, we will fetch Network status via 2 methods in android studio using Java.
You can use any latest version of Android Studio. This tutorial was written using Android Studio 4.1.

Fetch network status in Android Studio

Create a new project with name as Codespeedy and package name as org.codespeedy and min android version as 26.

Code:

Since we want network status so we need to mention this permission in manifest.xml file.
Write this in manifest.xml file: (manifest.xml file)

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

Now create a New Java File with name NetworkUtil.java which will have code to fetch network status for our android application.
Write this code in that NetworkUtil.java file:

 
package org.codespeedy;

import android.app.Application;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.NetworkRequest;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

public class NetworkUtil extends AndroidViewModel {

    public NetworkUtil(@NonNull Application application) {
        super(application);
    }

    private static MutableLiveData<Boolean> mutableLiveDataNetworkStatus = new MutableLiveData<>();

    public static MutableLiveData<Boolean> getMutableLiveDataNetworkStatus() {
        return mutableLiveDataNetworkStatus;
    }

    public static void setConnectivityTracking(Context context) {
        ConnectivityManager.NetworkCallback mCallback;
        ConnectivityManager mCManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest request = new NetworkRequest.Builder().build();
        mCallback=new ConnectivityManager.NetworkCallback() {
            @Override
            public void onLost(@NonNull Network network) {
                super.onLost(network);
                mutableLiveDataNetworkStatus.postValue(false);
            }
            @Override
            public void onAvailable(@NonNull Network network) {
                super.onAvailable(network);
                mutableLiveDataNetworkStatus.postValue(true);
            }
        };

        // now register the above things
        assert mCManager != null;
        mCManager.registerNetworkCallback(request,mCallback);
    }

   
    // needs to be called to get info about net E.g on Button Click
    public static Boolean getConnectivityStatus(Context context) {
        Boolean status = null;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert cm != null;
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) {
            return true;
        } else {
            status = false;
            return status;
        }
    }

}

In the above code, first we get the Network Service and then we add a callback to listen to change in internet connectivity status, and then accordingly change the value of our mutableLiveDataNetworkStatus variable.
The getConnectivityStatus() function gets us the network status instantly whereas the function setConnectivityTracking() is used to constantly monitor the network status.

Here we are using MutableLiveData which is like a broadcaster to all the files in which this is declared.
Whenever a variable of MutableLiveData type is manipulated a message is broadcasted to all the listeners of this variable and then appropriate action can be taken at the listener end.

Show internet status

Now, In the MainActivity.java you need to write this code:

package org.codespeedy;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        NetworkUtil.setConnectivityTracking(getApplicationContext());

        // To get the connectivity status one time when the application is opened
        if(NetworkUtil.getConnectivityStatus(getApplicationContext()))
        {
            // Some Task
        }
        else
        {
            // Some Task
        }

        // To get the Internet Connectivity Status as soon as its changed (REPEATEDLY)
        NetworkUtil.getMutableLiveDataNetworkStatus().observe(this,(internet)->{
            if(internet)
            {
                Toast.makeText(this, "GOT Internet ACCESS", Toast.LENGTH_SHORT).show();
            }
            else
            {
                Toast.makeText(this, "NO Internet ACCESS", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

Here, we simply set the network tracking from the context of MainActivity.java file.
And then we setup the listener to network change using NetworkUtil.getMutableLiveDataNetworkStatus().observe() function

Now all is done, run the app using USB debugging (Recommended), and see the change in network by the Toasts created by the app.

show internet status in android studio

 

Got_Internet_Access

 

In case it doesn’t work make sure that the gradle files have proper versions:

Build.gradle (Project: Codespeedy)

Build.gradle (Module: Codespeedy:app)

gradle-wrapper-properties:

Leave a Reply

Your email address will not be published.