繁体   English   中英

一定时间后如何停止requestLocationUpdates()?

[英]How to stop requestLocationUpdates() after a certain amount of time?

在我的Android应用程序中,我使用GoogleApiClient处理定位服务。 当我通过以下方式调用requestLocationUpdates()时,一切工作正常:

locationProvider.requestLocationUpdates(mGoogleApiClient, locationRequest, (LocationListener) thisFragment);

在我的活动的onCreate()方法中初始化了mGoogleApiClient位置:

private GoogleApiClient mGoogleApiClient;
[...]

// onCreate() method in my activity
mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addApi(Plus.API, Plus.PlusOptions.builder().build())
    .addApi(LocationServices.API)
    .addScope(new Scope("email"))
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();

locationProviderlocationRequest是在我的片段的onAttach()方法中初始化的, onAttach()方法还实现了com.google.android.gms.location.LocationListener

//onAttach() method in my fragment
this.locationProvider = LocationServices.FusedLocationApi;

this.locationRequest = new LocationRequest();
this.locationRequest
    .setInterval(Constants.GOOGLE_LOCATION_INTERVAL)
    .setFastestInterval(Constants.GOOGLE_FASTEST_LOCATION_INTERVAL)
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

问题在于,有时用户可能会要求在室内环境中检索其位置,因此我想在一定时间后终止requestLocationUpdates()请求。

到目前为止,我已经尝试了以下解决方案,但没有成功:

1) 使用Looper和Handler 实际上,此解决方案在旧的LocationManager效果很好。

Looper looper = Looper.myLooper();
Handler handler = new Handler(looper);

handler.postDelayed(new Runnable() {
@Override
    public void run() {
        locationProvider.requestLocationUpdates(mGoogleApiClient, locationRequest, (LocationListener) thisFragment, looper);
    }
}, Constants.LOCATION_TIMEOUT_MS);

2) 仅使用处理程序

Handler handler = new Handler();

handler.postDelayed(new Runnable() {
@Override
    public void run() {
        locationProvider.requestLocationUpdates(mGoogleApiClient, locationRequest, (LocationListener) thisFragment);
    }
}, Constants.LOCATION_TIMEOUT_MS);

但是,在两种情况下,超时(由Constants.LOCATION_TIMEOUT_MS表示)永远不会过期。 GPS服务持续不断。

首先,这两个代码是相同的:

Looper looper = Looper.myLooper();
Handler handler = new Handler(looper);

Handler handler = new Handler();

如果检查源代码,则可以看到Handler的空构造函数在内部使用Looper.myLooper();

我不确定在哪里认为这可能会取消请求,时间过后,您会再次调用requestLocationUpdates 因此,是的,它将继续尝试获取GPS锁定。

我会建议您两种方法。

  1. 第一个比较容易,但是我不确定它的效果如何,因为我仅将其用于被动位置更新。 根据您的请求使用expiration时间,在该到期时间之后,定位服务应自动退出。

     locationRequest.setExpirationDuration(Constants.LOCATION_TIMEOUT_MS); 
  2. 第二步是使用正确的方法,即removeLocationUpdates

     locationProvider.removeLocationUpdates( mGoogleApiClient, (LocationListener) thisFragment); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM