2013-02-22 106 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