Reputation: 3262
How do I stop the FusedLocation listener for updates? This is how I set it up:
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// Write a message to the database
};
};
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
null /* Looper */);
}
How to stop listening for location updates in the onStop
method for example?
Upvotes: 0
Views: 834
Reputation: 41
The official documentation recommends stop locations in onPause method and restart updates in onResume method.
The code will be something like this:
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void stopLocationUpdates() {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
@Override
protected void onResume() {
super.onResume();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
private void startLocationUpdates() {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback,
null /* Looper */);
}
Check this link for more info: https://developer.android.com/training/location/receive-location-updates
Upvotes: 1