gpt4 book ai didi

android - onLocationChanged 在应用程序启动时被多次调用

转载 作者:行者123 更新时间:2023-11-29 14:45:05 25 4
gpt4 key购买 nike

我写了以下服务,想法是在应用程序启动时将用户位置发送到服务器,当用户移动超过 500m 时,问题是在启动时调用 onLocationChanged 3 次。

我无法理解它从哪里调用它 3 次。请指导我如何解决这个问题。

public class LocationUpdateService extends Service implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {



private static final long BACKGROUND_INTERVAL = 60000;

final private String TAG = LocationUpdateService.class.getSimpleName();
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private String LOCATION_PREF = "LOCATION_PREF";



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand: ");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(BACKGROUND_INTERVAL);
mLocationRequest.setFastestInterval(30000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(500);
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}

@Override
public void onLocationChanged(Location location) {
Log.i("Location Service", "onLocationChanged: " + location.toString());
saveLocationandReport(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
}

最佳答案

您无法控制onLocationChanged,它由位置服务管理。在您的情况下,您可以设置缓冲/等待时间,如果您在缓冲时间内进行了位置更新,您可以检查其与之前位置更新的准确性比较,哪个最适合使用它。

private int FASTEST_INTERVAL = 1000; // use whatever suits you
private Location currentLocation = null;
private long locationUpdatedAt = Long.MIN_VALUE;

@Override
public void onLocationChanged(Location location) {
boolean updateLocationandReport = false;
if(currentLocation == null){
currentLocation = location;
locationUpdatedAt = System.currentTimeMillis();
updateLocationandReport = true;
} else {
long secondsElapsed = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - locationUpdatedAt);
if (secondsElapsed >= TimeUnit.MILLISECONDS.toSeconds(FASTEST_INTERVAL)){
// check location accuracy here
currentLocation = location;
locationUpdatedAt = System.currentTimeMillis();
updateLocationandReport = true;
}
}
if(updateLocationandReport){
// send your location to server
}
}

关于android - onLocationChanged 在应用程序启动时被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41955998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com