【发布时间】:2016-12-08 09:06:24
【问题描述】:
我已经坚持了一个多星期了,我似乎无法弄清楚我到底做错了什么。我已阅读以下问题,但似乎都不适合我:
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 个与 GoogleApiClient 交互的 Java 方法:
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();
}
}
然后我在我的 onCreate() 方法中调用 buildGoogleApiClient() 并在我的 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();
}
如果有必要,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 客户端时显示 Toast 时,应用程序崩溃并告诉我 Google API 客户端尚未连接。
提前感谢您抽出时间来帮助我解决这个问题。如果我监督了一些非常明显的事情,请原谅我。
【问题讨论】:
标签: java android google-play-services google-api-client