To get the user's location using FusedLocationClient only after all the required permissions have been granted, you can follow these steps:
- First, declare the necessary permissions in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
- Next, define a constant for the permission request code:
private static final int PERMISSIONS_REQUEST_CODE = 100;
- Check if the required permissions are granted when starting your activity or fragment:
// Check if the required permissions are granted
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_CODE);
} else {
// Permissions already granted, call getLocation()
getLocation();
}
- Handle the permission request result in onRequestPermissionsResult():
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_REQUEST_CODE:
// If permission is granted, call getLocation()
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
} else {
// Permission was denied. Handle accordingly.
// For example, show a message or disable location-related functionality.
Toast.makeText(this, "Location permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
- In your getLocation() method, initialize the FusedLocationClient and request location updates:
private void getLocation() {
FusedLocationProviderClient fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
// Request location updates
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. Use it accordingly.
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
// Use the location data as needed
}
}
})
.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Handle failure
Toast.makeText(MainActivity.this, "Failed to get location", Toast.LENGTH_SHORT)
.show();
}
});
}
Make sure to handle runtime permission requests correctly and provide a meaningful explanation to the user when requesting the location permission.