我一直堅持這一個多星期了,我似乎無法弄清楚我到底做錯了什麼。我已閱讀下列問題,其中沒有一個似乎爲我工作:無法連接到Google API CLient?
Fatal Exception: java.lang.IllegalStateException GoogleApiClient is not connected yet
google api client callback is never called
Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet
我試圖做的是使用LocationServices API與Geofence類結合使用來檢查用戶是否在指定區域。問題似乎在於與Google API客戶端和/或Locationservices API進行通信。
我宣佈我的清單如下:
<service android:name=".GeofenceTransitionsIntentService" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="value of my key" />
</application>
我已經在我的項目申報2種Java方法,其與GoogleApiClient互動:)在
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public void startApiClient(){
if (mGoogleApiClient.isConnected()) {
Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
return;
//Of course the Toast is supposed to fire of when the user cannot
//connect to the google api. However when I make this code to run
//when the user cannot connect to google play services it just shows
//the toast and does not report me the error which is why I in this
//case made this code to run when the user is connected to google play services
}
try {
LocationServices.GeofencingApi.addGeofences
(mGoogleApiClient, getGeofencingRequest(), getGeofencePendingIntent()).setResultCallback(this); // Result processed in onResult(). This is also the line where the app seems to crash because it is unable to connect to the google api client
} catch (SecurityException securityException) {
securityException.notify();
}
}
然後我打電話buildGoogleApiClient(我的onCreate()方法並在我的onStart()方法中調用startApiClient():
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
…
buildGoogleApiClient();
}
_
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
startApiClient();
}
而如果neccessary,在onResult()方法:
public void onResult(Status status) {
if (status.isSuccess()) {
// Update state and save in shared preferences.
mGeofencesAdded = !mGeofencesAdded;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean(Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded);
editor.apply();
}
關於這個奇怪的是,一個連接實際上沒有實例化一段時間。當我告訴程序在用戶未連接時顯示Toast時,我的Android監視器告訴我已建立連接,但Toast仍然被觸發。但是,當我告訴程序在用戶連接到Google API Client時顯示Toast時,應用程序崩潰並告訴我Google API Client尚未連接。
提前感謝您抽出時間來幫助我。如果我監督一些非常明顯的事情,請原諒我。