Search code examples
androidandroid-wifi

Android 11 wifi SSID is unknown in background even when location permissions are granted


I tested this code in Android 11

val networkRequest = NetworkRequest.Builder().apply {
    addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
}.build()
        
connectivityManager.registerNetworkCallback(networkRequest, object : ConnectivityManager.NetworkCallback() {
    
    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        val wifiName = getCurrentlyConnectedName() ?: return
        val wifiMac = getCurrentlyConnectedMac() ?: return
        Timber.d("WifiStateManager onAvailable() called with: network = [$wifiName]")
    }

    override fun onLost(network: Network) {
        super.onLost(network)
        Timber.d("WifiStateManager onLost() called with: network = [$network]")
    }
})

And noticed a strange behavior. When the app is in the background wifi ssid is always <unknown> (please note that Location permission is granted 100%). When the app is in the foreground everything is OK and I get the correct wifi ssid.

Why this is happening? How to get wifi SSID even when the app is in the background on Android 11?


Solution

  • Strange this hasn't been answer sooner.

    Location permission has now a special case for background access on Android 11+. One app can be granted access to location permission, but only in foreground. Background location permission requires a special request on Play Console to be published and get the corresponding permission:

    android.permission.ACCESS_BACKGROUND_LOCATION
    

    Starts with targeting API 29 I believe which is mandatory already on Play Store.