FusedLocationApi.getLastLocation always null
I think there is a small miss which is not visible to me in the code shown.
The mGoogleApiClient
is built but seems not connected.You can verify this by calling mGoogleApiClient.isConnected()
.
You can just override the onStart method and call connect there. Or you can override onResume()
in case you want to access the location whenever ur activity is visible.
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
As in this post said, The fused Location Provider will only maintain background location if at least one client is connected to it.
But we can skip the process of launching the Google Maps app to get last location by following way.
What we need to do is
- We have to request location update from FusedLocationProviderClient
- Then we can get the last location from FusedLocationProviderClient, it wouldn't be null.
Request Location
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
//TODO: UI updates.
}
}
}
};
LocationServices.getFusedLocationProviderClient(context).requestLocationUpdates(mLocationRequest, mLocationCallback, null);
Get last location
LocationServices.getFusedLocationProviderClient(context).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
//TODO: UI updates.
}
});
For best result requestLocationUpdates in onStart() of the Activity, and then you can get last location.
The fused Location Provider
will only maintain background location if at least one client is connected to it. Now just turning on the location service will not guarantee to store the last known location.
Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and getLastLocation()
is invoked right away in onConnected()
, that might not be enough time for the first location to arrive..
I suggest you to launch the Maps app first, so that there is at least some confirmed location, and then test your app.