为android requestSingleUpdate设置超时

Anj*_*Man 20 android android-location

我正在使用带有LocationListener的android LocationManager库的例程requestSingleUpdate()reoutine .我试图实现的功能是用户可以按下按钮,应用程序将获取其当前位置并执行反向地理编码以获取大致地址.

我的问题是,根据设备的网络情况,获取位置可能需要很长时间.如何实现超时,导致我的'requestSingleUpdate()'放弃并告诉用户找出他们自己的血腥地址?

我的代码:

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);
Run Code Online (Sandbox Code Playgroud)

Dan*_*lau 35

LocationManager似乎没有超时机制.但是LocationManager确实有一个名为的方法removeUpdates(LocationListener listener)可以用来取消指定的任何回调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);
Run Code Online (Sandbox Code Playgroud)

我不确定如果你locationManager.removeUpdates(myListener) 获得位置打电话会发生什么.你可能想在打电话之前检查一下removeUpdates.或者,你可以onLocationChanged在回调中的方法中添加这样的东西(也可能添加到其他方法):

    myHandler.removeCallbacks(myRunnable); // where myRunnable == the above Runnable 
Run Code Online (Sandbox Code Playgroud)

  • 另外,如果由于某种原因无法引用myRunnable,则可以使用myHandler.removeCallbacksAndMessages(null); 代替 (4认同)