2013-02-22 69 views
15

我正在使用android LocationManager库的例程requestSingleUpdate()例程,其中LocationListener。我试图实现的功能是,用户可以按下按钮,应用程序将获得其当前位置并执行反向地理编码以获取大致地址。为Android请求设置超时更新

我的问题是,根据设备的网络情况,获取定位可能需要很长时间。我如何实现一个超时会导致我的'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); 

回答

30

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 
+3

此外,如果您不能引用myRunnable出于某种原因,你可以使用将myHandler。 removeCallbacksAndMessages(NULL);代替 – 2013-11-24 10:16:26