When I check Android tutorials and/or the Android official documentation, it seems multiple different ways are there to query location. I am confused as I am not sure which way is the right way or if documentation is outdated.
For example,
1) GoogleApiClient: In this way, it uses the Google API client
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
and then it queries locations like this
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
2) Location Manager: This way uses location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
3) FusedLocationApi (2nd style):
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations, this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
Which way should we use?
FusedLocationProvider
is the best way to get the location in Android right now.
You have mentioned two ways to use FusedLocationManager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
The problem with this approach above is it will provide you the last known location which may be null also so you need to check for null also.
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
In this approach above, you are registering a fusedlocationListener which will on successfully registering will invoke the onSuccess method and will provide the location object which again may be null here.Usually in device reboot cases the last known location is null.There are some other cases also. I would advise you to use the second approach as it is using fusedlocationprovider to get the last known location as it is more efficeint.