为android requestSingleUpdate设置超时
我正在使用android库的例程requestSingleUpdate()reoutine和一个。我尝试实现的功能是,用户可以按下一个按钮,应用程序将获得其当前位置,并执行反向地理编码以获得大致地址 我的问题是,根据设备的网络状况,获取位置修复可能需要很长时间。我如何实现超时,使我的'requestSingleUpdate()'放弃并告诉用户找到自己的地址 我的代码:为android requestSingleUpdate设置超时,android,android-location,Android,Android Location,我正在使用android库的例程requestSingleUpdate()reoutine和一个。我尝试实现的功能是,用户可以按下一个按钮,应用程序将获得其当前位置,并执行反向地理编码以获得大致地址 我的问题是,根据设备的网络状况,获取位置修复可能需要很长时间。我如何实现超时,使我的'requestSingleUpdate()'放弃并告诉用户找到自己的地址 我的代码: LocationManager locationManager = (LocationManager) getSystemSe
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
locationManager.requestSingleUpdate(criteria, new LocationListener(){
@Override
public void onLocationChanged(Location location) {
// reverse geo-code location
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
}, null);
LocationManager
似乎没有超时机制。但是LocationManager
确实有一个名为的方法,您可以使用该方法取消指定LocationListener
上的任何回调
因此,您可以使用以下伪代码实现自己的超时:
final LocationManager locationManager
= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// ...
final LocationListener myListener = new LocationListener() {
//... your LocationListener's methods, as above
}
Looper myLooper = Looper.myLooper();
locationManager.requestSingleUpdate(criteria, myListener, myLooper);
final Handler myHandler = new Handler(myLooper);
myHandler.postDelayed(new Runnable() {
public void run() {
locationManager.removeUpdates(myListener);
}
}, MY_TIMEOUT_IN_MS);
如果您在获得位置后调用locationManager.removeUpdates(myListener)
,我不确定会发生什么。在调用removeUpdates
之前,您可能需要检查一下。或者,您可以将类似的内容添加到回调中的onLocationChanged
方法中(也可能添加到其他方法中):
此外,如果由于某种原因无法引用myRunnable,则可以使用myHandler.removeCallbacksAndMessages(null);相反
myHandler.removeCallbacks(myRunnable); // where myRunnable == the above Runnable