Skip to content Skip to sidebar Skip to footer

Android -> Get Current Network Type On Android 10 And Below

How can I get current network type? I found tis solution: val info = connectivityManager.activeNetworkInfo if (info == null || !info.isConnected()) return '-' // not connected if (

Solution 1:

NetworkInfo class was deprecated in API 29. So you need to replace the deprecated methods with those mentioned in their notes.

You can use this method for newer API levels:

fungetNetwork(): String {
    val connectivityManager =
        context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
    val nw = connectivityManager.activeNetwork ?: return"-"val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return"-"when {
        actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> return"WIFI"
        actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> return"ETHERNET"
        actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
            val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
            when (tm.dataNetworkType) {
                TelephonyManager.NETWORK_TYPE_GPRS,
                TelephonyManager.NETWORK_TYPE_EDGE,
                TelephonyManager.NETWORK_TYPE_CDMA,
                TelephonyManager.NETWORK_TYPE_1xRTT,
                TelephonyManager.NETWORK_TYPE_IDEN,
                TelephonyManager.NETWORK_TYPE_GSM -> return"2G"
                TelephonyManager.NETWORK_TYPE_UMTS,
                TelephonyManager.NETWORK_TYPE_EVDO_0,
                TelephonyManager.NETWORK_TYPE_EVDO_A,
                TelephonyManager.NETWORK_TYPE_HSDPA,
                TelephonyManager.NETWORK_TYPE_HSUPA,
                TelephonyManager.NETWORK_TYPE_HSPA,
                TelephonyManager.NETWORK_TYPE_EVDO_B,
                TelephonyManager.NETWORK_TYPE_EHRPD,
                TelephonyManager.NETWORK_TYPE_HSPAP,
                TelephonyManager.NETWORK_TYPE_TD_SCDMA -> return"3G"
                TelephonyManager.NETWORK_TYPE_LTE,
                TelephonyManager.NETWORK_TYPE_IWLAN, 19 -> return"4G"
                TelephonyManager.NETWORK_TYPE_NR -> return"5G"else -> return"?"
            }
        }
        else -> return"?"
    }
}

Post a Comment for "Android -> Get Current Network Type On Android 10 And Below"