Certainly! You can implement a settings screen where the user can choose between "Approximate Location" and "Precise Location". Based on their choice, you can then request the appropriate permission. Here's how you can achieve this:
You can use SharedPreferences
to store the user's choice. Provide two radio buttons or a switch/toggle for the user to select between "Approximate Location" and "Precise Location".
Before requesting location, check the user's choice from SharedPreferences
:
SharedPreferences preferences = getSharedPreferences("app_settings", MODE_PRIVATE);
String locationPreference = preferences.getString("location_preference", "approximate"); // default to approximate
if ("approximate".equals(locationPreference)) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_APPROXIMATE);
}
} else if ("precise".equals(locationPreference)) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_PRECISE);
}
}
Override the onRequestPermissionsResult
method to handle the result of the permission request:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_APPROXIMATE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted for approximate location
// Fetch the location using NETWORK_PROVIDER
} else {
// Permission denied
}
} else if (requestCode == REQUEST_CODE_PRECISE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted for precise location
// Fetch the location using GPS_PROVIDER
} else {
// Permission denied
}
}
}
Based on the user's choice and granted permission, fetch the location using either NETWORK_PROVIDER
(for approximate) or GPS_PROVIDER
(for precise).
- Always provide a rationale to the user if they deny the permission, explaining why the app needs the location.
- Consider the scenario where a user might change their preference. You should handle permission revocation and re-requesting permissions accordingly.
- As always, prioritize user privacy and inform them about how their location data will be used.