在片段中使用enableAutoManage()

Ham*_*jan 24 android google-api-client android-fragments google-places-api

还有其他方法可以连接Google API客户端吗?

我使用自动完成的地方,我必须在MYFRAGMENT的某些地方使用此代码

mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                .addApi(Places.GEO_DATA_API)
                .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                .addConnectionCallbacks(this).build();
Run Code Online (Sandbox Code Playgroud)

我的问题

enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                    .addConnectionCallbacks(this).build();
Run Code Online (Sandbox Code Playgroud)

我不能处理它,因为当我替换我时this,getActivity()我有许多铸造问题

感谢您的帮助,如果这个问题很愚蠢,我很抱歉.

Mat*_*ape 61

如果你想使用enableAutoManage那么你必须扩展你的活动FragmentActivity.它所做的回调是自动管理GoogleApiClient工作所必需的.因此,最简单的解决方案是添加extends FragmentActivity到您的活动中.然后你的演员表不会失败并导致应用程序在运行时崩溃.

另一种解决方案是自己管理api客户端.您将从enableAutoManage构建器中删除该行,并确保您自己connect/ disconnect从客户端.最常见的地方是onStart()/ onStop().就像是...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
            .addApi(Places.GEO_DATA_API)
            .addConnectionCallbacks(this).build();
}

@Override
protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();
    mGoogleApiClient.disconnect();
}
Run Code Online (Sandbox Code Playgroud)

  • 它真的只是连接/断开吗?通过查看GoogleApiClient来源,它似乎做了更多的事情.我无法确定,因为很难读出他们混淆的代码.我只是不想从`FragmentActivity'扩展,因为我的应用程序无论如何都不支持旧的API级别.从'FragmentActivity'扩展也会带来更多问题(动画,不同的FragmentManager和LoaderManager.LoaderCallbacks),所以我最好留在`Activity`.但我想模仿`enableAutoManage()`的确切行为. (5认同)
  • 我肯定会建议你查看新的GeoDataClient类.它可以让您省去处理GoogleApiClient类的麻烦.(https://developers.google.com/android/reference/com/google/android/gms/location/places/GeoDataClient) (3认同)