ACCESS_BACKGROUND_LOCATION Not Working on Lower Than Q (29) Android Versions

Viewed 4297

My app is targeting Android API 28.

According to the documentation, I should be requesting ACCESS_BACKGROUND_LOCATION, along with ACCESS_FINE_LOCATION when running on Android API < 29.

I have tried doing this but in onRequestPermissionResults(), ACCESS_BACKGROUND_LOCATION is never granted and returns PackageManager.PERMISSION_DENIED. I was under the impression this would be implicitly granted when requesting another foreground permission on < 29.

Alternatively, I can remove the permission from the request on API < 29 and everything seems to work as expected but I am conscious that I would be going against the documentation.

Question

Can I omit an explicit request for the ACCESS_BACKGROUND_LOCATION on Android versions < 29 and still work as expected whilst conforming to documentation in API 29 which works?

1 Answers

The documentation states:

If your app targets Android 10 (API level 29) or lower, complete the following steps to request ACCESS_BACKGROUND_LOCATION:

  1. Include the ACCESS_BACKGROUND_LOCATION permission, as well as either the ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission, in your app's manifest.

  2. Request the ACCESS_BACKGROUND_LOCATION permission, as well as one of the other location permissions: ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION. You can request these permissions in a single operation.

This is a little ambiguous because they don't mention specifics about how to implement, but the ACCESS_BACKGROUND_LOCATION was added in API 29, so it doesn't exist in API 28 and lower.

Apparently this wasn't the case in the past, but now if you try to use it for lower API levels, you'll get a warning:

enter image description here

You can just omit the request to ACCESS_BACKGROUND_LOCATION on API 28 or lower:

private fun requestLocationPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        ActivityCompat.requestPermissions(
                this,
                arrayOf(
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_BACKGROUND_LOCATION
                ),
                MY_PERMISSIONS_REQUEST_LOCATION
        )
    } else {
        ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                MY_PERMISSIONS_REQUEST_LOCATION
        )
    }
}

Complete code available here: https://stackoverflow.com/a/40142454/4409409

Related