在我的应用程序中,我需要获取用户位置(一次拍摄,而不是连续跟踪),以计算路线。因此,位置需要尽可能准确,但我不希望用户在我的应用程序尝试获取准确位置时等待太长时间。
我正在使用Google Play服务地址api:
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setNumUpdates(1);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,locationRequest, this);
mLocationHandler.sendEmptyMessageDelayed(0, 15000); // Time out location request
我有Handler mLocationHandler,它在15秒后取消了locationRequest,因为我不想让用户等待太长时间。
有没有办法,如果高精度位置超时,我怎么能尝试得到不那么准确的位置?
答案 0 :(得分:3)
你可以在超时后尝试这个,
Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
它将为您提供最后的已知位置,并检查准确性是否优于您从位置更新获得的准确性。
更新您的更新,如下所示:
final LocationRequest REQUEST = LocationRequest.create()
.setInterval(16)
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
这将确保您有更新。然后,您可以减少超过一秒的超时时间。然后你可以删除locationupdaterequest,如下所示:
if(mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
答案 1 :(得分:1)
我使用外部库:Android-ReactiveLocation。查看Cooler examples
部分,其中列出了您想要的内容:
LocationRequest req = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setExpirationDuration(TimeUnit.SECONDS.toMillis(LOCATION_TIMEOUT_IN_SECONDS))
.setInterval(LOCATION_UPDATE_INTERVAL);
Observable<Location> goodEnoughQuicklyOrNothingObservable = locationProvider.getUpdatedLocation(req)
.filter(new Func1<Location, Boolean>() {
@Override
public Boolean call(Location location) {
return location.getAccuracy() < SUFFICIENT_ACCURACY;
}
})
.timeout(LOCATION_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS, Observable.just((Location) null), AndroidSchedulers.mainThread())
.first()
.observeOn(AndroidSchedulers.mainThread());
goodEnoughQuicklyOrNothingObservable.subscribe(...);