For my app, I am trying to pull a fresh location only once to show nearby points of interest. I don't want to pull a cached location because the points of interests are displayed in order of distance from the current location, so the most current coordinates are very important
I have the following code below, but I find that sometimes it doesn't actually pull a current location (and instead seems to show the last pulled location upon requesting location again. What can I do to modify in order to pull the freshest single location in one action?
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
mLocationRequest = new LocationRequest.Builder(Priority.PRIORITY_BALANCED_POWER_ACCURACY)
.setWaitForAccurateLocation(true)
.setMaxUpdates(1)
.build();
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
if (locationResult == null) {
// Request update again if location is null
mFusedLocationClient.requestLocationUpdates(mLocationRequest, this, Looper.getMainLooper());
} else {
mLocation = locationResult.getLastLocation();
mLatitude = String.valueOf(mLocation.getLatitude());
mLongitude = String.valueOf(mLocation.getLongitude());
getClosestPOI(mLatitude, mLongitude);
}
}
};
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper());
Try this: Add the following to your code:
Update: First make sure your target device has installed Google play service using this post otherwise this method (i.e. FusedLocation) will return null location and you have to use LocationManager instead.