Home >Java >javaTutorial >How to Request Location Permissions in Android at Runtime?
When working with location-related features in Android apps, it is crucial to request user permission to access their device's location. This article will guide you through the necessary steps to request the required permissions:
In your AndroidManifest.xml file, declare the following permissions:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Inside your activity or fragment, request the permissions at runtime. You can do this by calling the requestPermissions method:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
Replace "MY_PERMISSIONS_REQUEST_LOCATION" with a unique request code.
Override the onRequestPermissionsResult method to handle the result of the permission request:
@Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted. // Proceed with your location-based tasks. } else { // Permission denied. // Handle the lack of permission. } break; } } }
Once you have obtained the permission, you can use the appropriate location API to access the device's location information.
If you are experiencing issues, check the following:
Additional Notes:
The above is the detailed content of How to Request Location Permissions in Android at Runtime?. For more information, please follow other related articles on the PHP Chinese website!