简体   繁体   中英

Good way for detecting if a device is connected to the internet in Android using Java

I am trying to make a function that detects if an user is connected to the internet so that I can request a new interstitial ad in case this function returns true. This is the function I made, but now it is deprecated because it is using deprecated API. Actually this function only detects if the user is connected to a network. So I don´t know which option would be better for the new function I want to make as this one is deprecated, to detect if the user is connected to a network as I made or to check if the user is actually connected to the internet if the use of this function will be to request an interstitial ad if it returns true as I have said.

This is the function I made, but now it needs to be changed because 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;
    }

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

I have searched for information but I have only found current awnsers but they were fot Kotlin, not Java...

You could for instance ping an external address that is always reachable, such as IP 8.8.8.8 (Google). See here how you do it.

But normally you can just skip it, as interstitial ads are loaded in the background and won't throw an exception if there is no connection, at least for Admob and most major ad networks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM