2015-10-18 37 views
0

這是在創建GoogleApiClient時調用的代碼。所有這些都會檢索用戶的最後位置。如何使回調中的實例變量更新在主線程中發生?

//omitted code 

@Override 
public void onConnected(Bundle bundle) { 
    Location location = LocationServices.FusedLocationApi.getLastLocation(mApiClient); 
    if (location != null) { 
     mLongitude = String.valueOf(location.getLongitude()); 
     mLatitude = String.valueOf(location.getLatitude()); 
     Log.d(TAG, mLongitude + "___" + mLatitude); //this one doesn't return null 
    } else { 
     Log.d(TAG, "Location is null"); 
     LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient, mLocationRequest, this); 
    } 
} 

這是谷歌的API客戶端:

private void buildGoogleApiClient() { 
    mApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .build(); 
} 

這個片段是從我的onCreate()方法:

buildGoogleApiClient(); 
Log.d(TAG, mLongitude + "___" + mLatitude); //this one returns null 

所以當代碼獲取運行,我建立一個谷歌API客戶端和onConnected方法被調用。在該方法內部,我將更新實例變量mLongitude和mLatitude變量。但是在日誌中,它們返回爲空。我想知道爲什麼發生這種情況,所以我把另一個日誌INSIDE放在我的onConnected()方法的if語句中,就像你在第一個代碼塊中看到的那樣,這個成功地帶回了經度和緯度。我不知道爲什麼它不更新實例變量。我相信這是因爲回調沒有在主線程上運行,所以日誌發生在更新之前。於是,我就這樣在主線程中運行代碼:

runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       buildGoogleApiClient(); 
      } 
     }); 
Log.d(TAG, mLongitude + "___" + mLatitude); 

不幸的是,這並不工作要麼。我搜索了與這個主題相關的東西,並嘗試在我的代碼中實現它們,但是沒有一個似乎工作,因爲我甚至不知道這個問題的真正原因。

任何人都知道如何解決這個問題?

謝謝

+0

你的「onLocation()」方法是怎樣的?這是你應該更新你的位置,而不是在onConnected –

+0

我沒有「onLocation()」方法。我只是遵循Android文檔,它沒有告訴我這個。我只想抓住用戶的經度和緯度一次 – Kevin

+0

那麼你是如何創建你的'''mLocationRequest''' –

回答

1

buildGoogleApiClient調用是異步的。數據稍後會回來 - 您的變量將在通話完成之前打印。

您需要找到一種方法來等待數據返回。有很多方法可以實現這一點。

編輯:

只是爲了驗證,您可以在非UI線程運行一個循環,等待數據的改變......這樣的:

new Runnable() { 
     @Override 
     public void run() { 
      while (mLongitude == null) { 
       wait(100); 
      } 
      Log.d(TAG, mLongitude + "___" + mLatitude); 
     } 
    }); 

您可能希望完善它,但有很多方法可以等待,而不是在UI線程上。但問題在於,一旦數據可用,您想要對數據進行處理。如果您需要更新數據庫與UI,那麼您需要不同的實現。從根本上說,它的實施與一樣。

+0

這是什麼常見的方法呢? – Kevin

+0

@Kevin常用的方法是[實現回調](http://stackoverflow.com/questions/3398363/how-to-define-callbacks-in-android),以便在調用完成後,回調可以做下一步。換句話說,使用['GoogleApiClient.ConnectionListener.onConnected()'](https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks.html#onConnected (android.os.Bundle)) –

相關問題