【问题标题】:Set a time-out for android requestSingleUpdate为 android requestSingleUpdate 设置超时
【发布时间】:2013-02-08 08:25:15
【问题描述】:

我正在使用带有LocationListener 的android LocationManager 库的例程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);

【问题讨论】:

    标签: android android-location


    【解决方案1】:

    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 
    

    【讨论】:

    • 另外,如果你因为某些原因不能引用 myRunnable,你可以使用 myHandler.removeCallbacksAndMessages(null);而是
    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 2018-07-08
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2010-09-27
    相关资源
    最近更新 更多