1

我在我的應用程序中使用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也正常發生。

我認爲有兩種可能性此錯誤:

  1. 的onMapReady方法被調用onStart(不太可能)

  2. 調用OnStop方法斷開連接客戶端是提供給onMapReady之前之前叫方法

無論對錯誤的某些解決方案將不勝感激。

鏈接到全要點低於: https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac

+0

我認爲,第一種可能是您的錯誤的原因。因爲將它放在onStart()上是一個壞主意。 –

+0

@mihir raj事實並非如此,實際上我試圖在google api客戶端連接之前創建geofences。 onMapReady在調用onConnected方法之前請求google api客戶端。所以我將onMapReady方法中的所有geofence代碼移動到onConnected方法,並且它工作正常。 – 4blun3kin

回答

1

我找到了答案,以我自己的問題。

顯然,Google API客戶端連接與Google地圖連接是分開的。 API客戶端專門用於位置服務。

因此,我需要在API連接建立之後建立geofencing。

因此,我將所有地理圍欄代碼移入了onConnected。

@Override 
public void onConnected(Bundle savedInstanceState) { } 

解決了這個問題。

看看更新的要點: https://gist.github.com/serceberka/0935e185e663a3be13eb13f4b9e0d5ac

+0

您的解決方案是正確的。在調用connect方法()後,只要連接請求完成,就會自動調用onConnected()方法。因此,您必須僅在onConnected()方法中寫入任務,否則您將使用GoogleApiClient對象產生空指針異常。 您可以參考此文檔以瞭解有關onConnected()方法的更多信息。鏈接:https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks –