如何停止FusedLocation侦听器进行更新? 这是我的设置方式:
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 */);
}
例如,如何停止使用onStop
方法监听位置更新?
答案 0 :(得分:1)
官方文档建议使用onPause方法停止位置,并使用onResume方法重新启动更新。
代码将如下所示:
@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 */);
}
检查此链接以获取更多信息:https://developer.android.com/training/location/receive-location-updates