After several (unsuccessful) attempts to make my applications compliant about the background access to the location, I decided to re-structure my code in order to remove the ACCESS_BACKGROUND_LOCATION
permission from the manifest
.
My application
necessarily needs to get the location of the device at certain times (specifically I need the coordinates), what I'm interested in knowing is:
without using the permission mentioned above, how do I get, in foreground, the location of the device?
is it possible to do it with a one-time call without using services etc?
I thought about using this code, do you think it could be enough?
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// Logic to handle location object
}
}
});
or something like this:
LocationManager mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location location = mLocationManager.getLastKnownLocation(provider);
if (location == null) {
continue;
}
if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = location;
}
}
is there a better way to do this?
To get the last know location you need to have following permissions declared in Manifest file.
"android.permission.ACCESS_FINE_LOCATION"
Then you may use Fused Location Provider as you have used.
Now if you want periodic updates you may want to register for those updates using following callback.
requestLocationUpdates
passed with a request object and callback to receive updates.
Helpful links with exact code: Request Updates