Я застрял на этом уже более недели, и я не могу понять, что именно я делаю неправильно. Я прочитал следующие вопросы, ни один из которых, кажется, работает для меня:Не удается подключиться к API Google API?
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, чтобы проверить, находится ли пользователь в указанной области. Проблема, похоже, связана с общением с API-интерфейсом API Google API и/или Locationservices.
я заявил следующее в своем манифесте:
<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() и вызов startApiClient() в моем методе onStart():
@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();
}
И в случае, необходимый, метод 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 все еще запускается. Однако, когда я говорю программе показывать Toast, когда пользователь подключен к клиенту API Google, приложение отключается и сообщает мне, что клиент API Google еще не подключен.
Заранее благодарим за то, что нашли время, чтобы помочь мне с этим. Пожалуйста, простите меня, если я буду наблюдать что-то очень очевидное.