phone 旋转后 GoogleAPIClient 未连接

GoogleAPIClient not connecting after phone rotated

我有一个 class 用于创建包含 GoogleApiClient 的地理围栏,目前有两个活动访问它(通过以下 this tutorial 创建)。我将 class 设置为非 UI 片段,因为据我所知(如果我错了请纠正我!)GoogleApiClient 需要附加到生命周期,并且是能够在多个位置连接它 我无法将它嵌入 activity.

在活动中,我创建了片段;

private GeofenceUtilityFragment geofenceUtils = new GeofenceUtilityFragment();

并将其添加到 activity;

if (savedInstanceState == null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().add(geofenceUtils, getString(R.string.fragment_key_geofence_utils)).commit();
}

当用户第一次导航到 activity 时,一切正常。但是,当应用程序旋转时(或可能导致重绘的任何其他事件发生),GoogleApiClient returns 一个空对象引用。

方法调用;

private void setGeofences(){
    if (!mGoogleApiClient.isConnected()){
        Toast.makeText(activityContext, "not connected", Toast.LENGTH_SHORT).show();
        return;
    }

真正令人困惑的是,在轮换之后,触发了 onConnected 回调,因此 API 客户端正在重新连接,但由于某种原因,当我尝试访问它时,我得到了一个空值。

这是显示两者的 Log 语句(中间切掉了一些额外的绒毛)

0387/com.example.android.bentheredonethat D/GeofenceUtilityFragment: onConnected has just been called

[...]

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.common.api.GoogleApiClient.isConnected()' on a null object reference
                                                                                      at geolocationtools.GeofenceUtilityFragment.setGeofences(GeofenceUtilityFragment.java:179)
                                                                                      at geolocationtools.GeofenceUtilityFragment.callGeofenceRoutine(GeofenceUtilityFragment.java:220)
                                                                                      at com.example.android.bentheredonethat.RouteDetailsActivity.startRouteButtonHandler(RouteDetailsActivity.java:321)

对这个很迷惑,所以任何帮助将不胜感激!如果有任何其他我可以提供的帮助,请告诉我,我会添加。

GoogleApiClient 可以附加到 Activity,并设置为自动管理,或者它可以附加到应用程序(或另一个 Singleton),并进行手动管理。您将它附加到非 ui 片段没有任何意义,因为它没有生命周期并且无法自动管理。
根据您的需要,扩展应用程序 class(Google 的说明),向其添加一个 GoogleApiClient 变量。在应用程序的onCreate中初始化,并处理onConnected回调。