Handling Android Location Permissions
To show a user's location on the map, your app must request and receive location permissions from the user. Since Android 6.0 (API level 23), permissions like location are requested at runtime, not only in the manifest. This means your app needs to check for permissions and handle the user's response.
Requesting permissions directly in your activity can lead to repetitive and hard-to-maintain code. The Maps SDK for Android provides utilities to simplify this process.
Permission flow overview
- Check if location permissions are already granted.
- If not, request permissions from the user.
- Respond to the user's choice:
- If granted, enable location features.
- If denied, explain why the permission is needed or disable location features.
Using the Maps SDK permission utilities
The Maps SDK provides a PermissionsManager utility to help you check and request permissions. It also provides a PermissionsListener interface to handle the user's response.
In your activity's onCreate method, you can check for permissions and request them if needed using these utilities. PermissionsListener is used when instantiating PermissionsManager to handle the user's response to the permission request.
You must also override onRequestPermissionsResult in your activity and pass the results to the PermissionsManager to make sure it can properly handle the response.
lateinit var permissionsManager: PermissionsManager
override fun onCreate(savedInstanceState: Bundle?) {
if (PermissionsManager.areLocationPermissionsGranted(context)) {
// Location permission granted, enable location features
} else {
permissionsManager = PermissionsManager(object : PermissionsListener {
override fun onExplanationNeeded(permissionsToExplain: List<String>) {
// Optionally show a dialog explaining why the app needs location permission
}
override fun onPermissionResult(granted: Boolean) {
if (granted) {
// Permission granted, enable location features
} else {
// Permission denied, show a message or disable location features
}
}
})
// Trigger the permission request
permissionsManager.requestLocationPermissions(this)
}
}
// Handle the result of the permission request and delegate to PermissionsManager
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
This approach keeps your permission logic organized and easier to manage. The PermissionsManager can also be used for other Android permissions.
See how the PermissionsManager and PermissionsListener are used to check permissions before showing the device location puck.
Best practices
- Always explain to users why your app needs location access, especially if they deny the request the first time.
- Only request permissions when you need them, not at app launch.
- Handle the case where the user denies the permission gracefully.