How to Request Location Permission at Runtime
In the Manifest file, it's crucial to include the necessary permissions for location access. However, simply adding permissions to the manifest won't suffice on devices running Android 6 or higher. To obtain location updates successfully, you need to request permission at runtime. Here's a step-by-step guide:
-
Check Permission Status:
- Use ContextCompat.checkSelfPermission() to verify whether the app has access to the required permissions (in your case, Manifest.permission.ACCESS_FINE_LOCATION).
-
Request Permission (if not granted):
- If permissions are not granted, use ActivityCompat.requestPermissions(). This will prompt the user to grant or deny permission.
-
Handle Permission Result:
- Override onRequestPermissionsResult(). This method will receive the result of the permission request and update the location manager accordingly.
In your code:
- You correctly add the location permissions to the manifest.
- You use ContextCompat.checkSelfPermission() to check permission status, but you don't request the permission if it's not granted.
- To resolve the issue, you need to request location permission using ActivityCompat.requestPermissions(), as shown in the updated Java and Kotlin code examples provided in the answer.
-
Start Location Updates (if permission granted):
- After permission is granted, use requestLocationUpdates() to receive location updates.
-
Pause/Resume Location Updates:
- Use onPause() and onResume() to pause and resume location updates when the activity is in the background or foreground, respectively.
The above is the detailed content of How to Properly Request Runtime Location Permission in Android?. For more information, please follow other related articles on the PHP Chinese website!