user16257123
user16257123

Reputation:

How to get Network Info - Android

This is my code below:

@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}

When I run the above code, I am getting a Deprecated warning saying that getActiveNetworkInfo and isConnected methods are deprecated.

I don't want to continue this code for any longer. What are some of the alternatives of the above code?

Can someone please help me? Thanks in Advance

Upvotes: 0

Views: 1034

Answers (1)

Vikas Choudhary
Vikas Choudhary

Reputation: 554

Below is my code which I use in my application to check if device is connected to network. It does not contain any deprecated code as of now.

Kotlin

private fun isInternetAvailable(): Boolean {
    var result = false
    val connectivityManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
    connectivityManager?.let {
        it.getNetworkCapabilities(connectivityManager.activeNetwork)?.apply {
            result = when {
                hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
                hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
                else -> false
            }
        }
    }
    return result
}

Java

public static boolean isInternetAvailable(Context context) {
    boolean result = false;
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
        if (networkCapabilities != null) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                result = true;
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                result = true;
            } else {
                result = false;
            }
        }
    }
    return result;
}

Read more about Connectivity Manager and Network Capabilities here.

Upvotes: 2

Related Questions