0

I have the

compileSdkVersion 29

and

targetSdkVersion 29

in my android app. And to check if there is a connection I use the next code:

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
return connectivityManager?.activeNetworkInfo?.isConnected ?: false

But with my targetSdk the activeNetworkInfo is deprecated. How can I check the connection status without deprecated methods and variables?

Alex D.
  • 1,424
  • 15
  • 40

2 Answers2

1

You can do it as below:

    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        val network = connectivityManager.activeNetwork
        val capabilities = connectivityManager.getNetworkCapabilities(network)
        return capabilities != null && (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || capabilities.hasTransport(
            NetworkCapabilities.TRANSPORT_CELLULAR
        ))
    }
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
0

Use ConnectivityManager.NetworkCallback instead, here is the link for documentation

Mohan Sai Manthri
  • 2,808
  • 1
  • 11
  • 26