【发布时间】:2015-07-17 09:30:56
【问题描述】:
在我的 Android 应用程序中,我使用 GoogleApiClient 来处理位置服务。当我通过以下方式调用requestLocationUpdates() 时,一切正常:
locationProvider.requestLocationUpdates(mGoogleApiClient, locationRequest, (LocationListener) thisFragment);
mGoogleApiClient 在我的活动的onCreate() 方法中初始化:
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();
而locationProvider 和locationRequest 在我的片段的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 服务一直在不停地工作。
【问题讨论】:
标签: android gps google-api location handler