[英]How to stop tracking location?
I have a location-based alerting app when a user enters near to particular area, he/she should be alerted. 当用户进入特定区域附近时,我有一个基于位置的警报应用程序,应该提醒他/她。 I need to stop tracking location after the alert is clicked once. 单击警报后,我需要停止跟踪位置。 But my app is continuously alerting the user. 但是我的应用不断提醒用户。 How to stop it? 如何停止呢? I included code to check the distance between the user current location and destination in location onChange
method. 我在位置onChange
方法中包含用于检查用户当前位置和目标之间距离的代码。
public void onLocationChanged(Location location) {
double lat1 = location.getLatitude();
double lon1 = location.getLongitude();
checkloc(lat1, lon1);
}
You might want to have a Flag, representing if the user was already warned, for instance: 您可能想要一个标志,代表是否已经警告过用户,例如:
boolean WAS_WAARNED = false;
void onLocationChanged(Location location) {
if(!WAS_WARNED){
WAS_WARNED = true;
checkloc(location.getLatitude(), location.getLongitude());
}
}
You'll want to stop requesting location updates. 您将要停止请求位置更新。 This can be done by calling removeLocationUpdates on your location client. 这可以通过在您的位置客户端上调用removeLocationUpdates来完成。
For example: 例如:
alertButton.setOnClickListener(view -> {
//Do some stuff.
if (mLocationClient != null){
mLocationClient.removeLocationUpdates(mLocationCallback)}
});
Here, mLocationClient is your FusedLocationProviderClient, and mLocationCallback is your LocationCallback (this will have the onLocationChanged method within it). 在这里,mLocationClient是您的FusedLocationProviderClient,而mLocationCallback是您的LocationCallback(其中将具有onLocationChanged方法)。 Since you check their location in the onLocationChanged method, there will no longer be updates to the location so the alert won't be created. 由于您在onLocationChanged方法中检查了它们的位置,因此将不再更新该位置,因此不会创建警报。 You could also call removeLocationUpdates in your checkloc method if they are in the correct location. 如果它们在正确的位置,也可以在checkloc方法中调用removeLocationUpdates。
Here is a link to the documentation for the FusedLocationProviderClient, giving more information. 这是FusedLocationProviderClient文档的链接,提供了更多信息。
Note: you may want to look up geofencing . 注意:您可能需要查找geofencing 。 It does something similar to what you want to do. 它执行的操作与您想要执行的操作相似。
First Approach-> Save alert clicked the flag to PrefUtils which is the most useable memory for save status. 第一种方法->保存警报单击了PrefUtils的标志,这是保存状态最可用的内存。 When a user clicks the alert you just set the status true and save it to prefUtils. 用户单击警报时,只需将状态设置为true并将其保存到prefUtils。
public void onLocationChanged(Location location) {
if(PrefUtils.getLoationStatus(getApplicationContext(), false)) {
double lat1=location.getLatitude();
double lon1=location.getLongitude();
checkloc(lat1,lon1);
PrefUtils.setLocationStatus(true);
}
}
Second Approach -> When the alert is clicked just set -> locationManager.removeUpdates(this); 第二种方法->单击警报时,只需设置-> locationManager.removeUpdates(this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.