Android 11 wifi SSID is unknown in background even when lcoation permissions is 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 notices 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?

2 answers

  • answered 2021-06-29 06:42 3c71

    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.

  • answered 2021-12-22 06:42 codezjx

    This is the correct behavior on Android 10+(API 29 and higher), declaring ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permissions is not enough.

    1. For foreground location:

    You also need to declare a foregroundServiceType of location in your Service to use foreground location.

    <service
        android:name="MyNavigationService"
        android:foregroundServiceType="location" ... >
        <!-- Any inner elements would go here. -->
    </service>
    

    Or if your code running in the Activity, the activity should be visible to the user.

    2. For background location:

    As 3c71 said, you should declare the ACCESS_BACKGROUND_LOCATION permission in your app's manifest in order to request background location access at runtime.

    Due to the Google Play location policy, it may reject apps which require background location permission. So, I think the foreground location should be a better choice.

    Official document: https://developer.android.com/training/location/permissions

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum