2016-03-03 173 views
-3

我首先使用Android LocationServices.SettingsApi檢查位置是否打開,如果不是,則使用Android documentation example顯示標準位置設置對話框。稍後,如果用戶啓用位置,我使用LocationServices.FusedLocationApi.getLastLocation()來獲取當前位置。這裏如下:如何檢查LocationServices.FusedLocationApi.getLastLocation()是否爲空?

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == ENABLE_LOCATION_REQUEST_CODE) { 
     switch (resultCode) { 
      case Activity.RESULT_OK: 
       Location location = LocationServices.FusedLocationApi 
             .getLastLocation(mGoogleApiClient); 
       while (location == null) { 
        location = LocationServices.FusedLocationApi 
         .getLastLocation(mGoogleApiClient); 
       } 
       break; 
      case Activity.RESULT_CANCELED: 
       Toast.makeText(this, "Location not enabled!", Toast.LENGTH_LONG).show(); 
       break; 
      default: 
       break; 
     } 
    } 
} 

LocationServices.FusedLocationApi .getLastLocation()發生在我的設備1秒左右啓用位置後,返回非空值。問題是我使用while語句直到LocationServices.FusedLocationApi .getLastLocation()返回非空值。我認爲我在UI Thread中做這件事的方式不對。也許我可以在後臺線程中做到這一點,但我想知道的是,有一些更好的原生方式。

回答

0

而不是使用後臺線程則可以使用Handler.postDelayed()

if(location==null){ 
    new android.os.Handler().postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
     } 
    }, 2000);//your waiting time.. I prefer 2 secs 
} 

Happy_Coding;