Eldestornillador
Eldestornillador

Reputation: 99

How to detect if the user is connected to the internet in android (java)

I had the following code that worked perfect to detect if the user was connected to the internet but I have noticed that it is using deprecated API :

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;



public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            //noinspection deprecation
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            for (NetworkInfo anInfo : info)
                if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }

        }
        return false;
    }

}

To let you understund I am using that function "isConnectingToInternet()" so that if it return true it will request an interstitial ad:

    private void CallNewInertial() {
        ConnectionDetector cd = new ConnectionDetector(Activityone.this);
        if (cd.isConnectingToInternet()) {
            requestNewInterstitial();
        }
    }

I have searched for API which is not deprecated and I have found the following 3: ConnectivityManager.NetworkCallback, ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties.

I don´t know how to make the same function using those non-deprecated API. I have also searched for similar posts but all of them were for Kotlin not for Java that is my case.

Upvotes: 0

Views: 54

Answers (0)

Related Questions