我在我的應用程序中使用geofencing。每當我嘗試添加geofences時,都會收到以下錯誤消息。android geofencing java.lang.IllegalStateException:GoogleApiClient尚未連接
IllegalStateException: GoogleApiClient is not connected yet
在AppCompatActivity onCreate方法我定義客戶端
/* Create a new google api client */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
,並在我的OnStart方法我連接到它,確保它不爲空
/* Connect to the API client */
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
但仍然給出了錯誤。
我AppCompatActivity實現等等OnMapReadyCallback和ResultCallback接口
針對我有一個重寫的方法
@Override
public void onMapReady(GoogleMap googleMap) {}
的onMapReady方法包含這個代碼行
LocationServices.GeofencingApi.addGeofences(
mGoogleApiClient,
getGeofencingRequest(),
getGeofencePendingIntent()
).setResultCallback(MapsActivity.this);
我已經定義getGeofencingRequest和getGeofencingPendingIntent私有方法,並重寫ResultCallback中的onResult方法。
我花了幾個小時在這個錯誤,似乎無法取得進展。該應用程序正常執行,直到AppCompatActivity啓動。 onCreate正常發生,onStart也正常發生。
我認爲有兩種可能性此錯誤:
的onMapReady方法被調用onStart(不太可能)
調用OnStop方法斷開連接客戶端是提供給onMapReady之前之前叫方法
無論對錯誤的某些解決方案將不勝感激。
鏈接到全要點低於: https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac
我認爲,第一種可能是您的錯誤的原因。因爲將它放在onStart()上是一個壞主意。 –
@mihir raj事實並非如此,實際上我試圖在google api客戶端連接之前創建geofences。 onMapReady在調用onConnected方法之前請求google api客戶端。所以我將onMapReady方法中的所有geofence代碼移動到onConnected方法,並且它工作正常。 – 4blun3kin