4

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?

1
  • I have the same problem, no answer ?
    – NizarETH
    Jun 3, 2021 at 9:47

2 Answers 2

4

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.