WifiManager getConnectionInfo() got deprecated in Android API level 31

Viewed 807

We uses Wifimanger getConnectionInfo() method to get SSID and BBSID of connected wifi. But starting with Andorid API level 31 , Android has deprecated the getConnectionInfo() method.

The solution that they have provided to use getTransportInfo() required minimum Android level 29 which we cannot target , given our 20 percent user still on Android API level below 29.

Can someone help with the alternative method to get connected wifi.

https://developer.android.com/reference/android/net/wifi/WifiManager#getConnectionInfo()

1 Answers

You can use NetworkCallback() instead. You need to pass FLAG_INCLUDE_LOCATION_INFO to NetworkCallback(), otherwise you will get "unknow ssid" only. Also you need the ACCESS_NETWORK_STATE and ACCESS_FINE_LOCATION permissions to make it work.

            val request = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .build()
            val networkCallback = object : ConnectivityManager.NetworkCallback(
                FLAG_INCLUDE_LOCATION_INFO) {
                override fun onCapabilitiesChanged(
                    network: Network,
                    networkCapabilities: NetworkCapabilities
                ) {
                    super.onCapabilitiesChanged(network, networkCapabilities)
                    val wifiInfo = networkCapabilities.transportInfo as WifiInfo
                    val ssid = wifiInfo.ssid
                }
            }
            connManager.registerNetworkCallback(request, networkCallback)

Refer to: https://developer.android.com/reference/kotlin/android/net/wifi/WifiManager#getConnectionInfo().

Related