我的FusedLocationProviderClient在我调用
后没有停止 fusedLocationClient.removeLocationUpdates(locationCallback);
GPS位置图标会无限期地显示在通知栏中,直到我手动终止服务。
我也在onDestroy()
方法中调用stopLocationUpdates。
要开始,我打电话:
fusedLocationClient.requestLocatonUpdates(locationRequest, locationCallback, null);
locationCallback是:
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location lastLocation = null;
for (Location location : locationResult.getLocations()) {
if (lastLocation != null) {
if (location.getTime() < lastLocation.getTime()) {
lastLocation = location;
}
} else {
lastLocation = location;
}
}
if (lastLocation != null) {
String msg1 = "Best location: http://www.google.com/maps/search/?api=1&query=" + lastLocation.getLatitude() + "%2C" + lastLocation.getLongitude();
sendSms(lastReceivedNumber, msg1);
}
stopLocationUpdates();
}
};
以下是stopLocationUpdates()
:
private void stopLocationUpdates() {
if (fusedLocationClient != null) {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
fusedLocationClient = null;
}
我无法理解为什么它不会停止。
任何帮助表示感谢。
答案 0 :(得分:1)
这是我做的:
private void startLocationUpdates() {
fusedLocationClient = new FusedLocationProviderClient(this);
locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location lastLocation = null;
for (Location location : locationResult.getLocations()) {
if (lastLocation != null) {
if (location.getTime() < lastLocation.getTime()) {
lastLocation = location;
}
} else {
lastLocation = location;
}
}
if (lastLocation != null) {
String msg1 = "Best location: http://www.google.com/maps/search/?api=1&query=" + lastLocation.getLatitude() + "%2C" + lastLocation.getLongitude();
sendSms(lastReceivedNumber, msg1);
}
stopLocationUpdates();
}
};
try {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} catch (SecurityException e) {
e.printStackTrace();
}
}
private void stopLocationUpdates() {
if (fusedLocationClient != null) {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
fusedLocationClient = null;
locationRequest = null;
locationCallback = null;
}
我只是将客户端归零,归零所有似乎都解决了问题。
现在我所要做的就是打电话给startLocationUpdates()
,它会照顾好自己,然后摧毁一切。