這是在創建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);
不幸的是,這並不工作要麼。我搜索了與這個主題相關的東西,並嘗試在我的代碼中實現它們,但是沒有一個似乎工作,因爲我甚至不知道這個問題的真正原因。
任何人都知道如何解決這個問題?
謝謝
你的「onLocation()」方法是怎樣的?這是你應該更新你的位置,而不是在onConnected –
我沒有「onLocation()」方法。我只是遵循Android文檔,它沒有告訴我這個。我只想抓住用戶的經度和緯度一次 – Kevin
那麼你是如何創建你的'''mLocationRequest''' –