为Android的requestSingleUpdate设置超时时间

21
我正在使用android LocationManager库中的LocationListener例程requestSingleUpdate()。我尝试实现的功能是,用户可以按下一个按钮,应用程序将获取其当前位置并执行反向地理编码以获取大致地址。
我的问题是,根据设备的网络情况,获取定位可能需要很长时间。如何实现超时,使我的'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);
1个回答

36

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);

如果在获取位置之后调用locationManager.removeUpdates(myListener),我不确定会发生什么。在调用removeUpdates之前,你可能需要检查一下这个情况。或者,你可以将以下内容添加到回调函数onLocationChanged中(以及可能的其他方法):

    myHandler.removeCallbacks(myRunnable); // where myRunnable == the above Runnable 

4
另外,如果由于某种原因无法引用 myRunnable,则可以使用 myHandler.removeCallbacksAndMessages(null);。 - Ahmet Noyan Kızıltan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接