Check Internet status on API 29 (Anroid Q)

Asked

Viewed 87 times

0

Good afternoon, I have the following method to check if the internet network is active at that time:

public static boolean isNetworkAvaliable(Context ctx) {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager != null) {
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        return (activeNetwork != null && activeNetwork.isConnected());
    } else {
        return false;
    }
}

But NetworkInfo as well as .getActiveNetworkInfo() were discontinued in API 29. Anyone knows of any synchronous solution for API 29?

Thank you in advance.

1 answer

2


public static boolean hasInternetConnection(Context context) {

    /*
    Taken from Johan's answer at: https://stackoverflow.com/a/35009615
     */

    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    Network network;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        network = connectivityManager.getActiveNetwork();
    } else
        return true;
    NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
    return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
}

source: https://www.programcreek.com/java-api-examples/? class=android.net.Connectivitymanager&method=getNetworkCapabilities

  • Thank you very much Luis, I made some changes to my situation, but it worked very well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.