7

I've started using Dagger2 to manage dependencies and I'm trying to understand how I can use DI to provide a singleton GoogleApiClient. The motivations for this are:

  • reduce boilerplate code: multiple Activities & Fragments require a GoogleApiClient
  • improve testability: currently these Activities and Fragments are not well tested

I want to provide a Singleton GoogleApiClient at the Application scope.

How do you handle callbacks? Whether you choose an auto-managed or manually-managed connection, there are some callbacks that must be handled:

  • GoogleApiClient.ConnectionCallbacks (manual only)
  • GoogleApiClient.OnConnectionFailedListener (both)
4

1 回答 1

7

您可以使用注入来创建客户端

 @Provides
    @Singleton
    GoogleApiClient providesGoogleApiClient(Context context) {
            return new GoogleApiClient.Builder(context)
                    .addApi(Places.GEO_DATA_API)
                    .addApi(LocationServices.API)
                    .build();
        }

然后管理您活动的回调

@Inject GoogleApiClient mGoogleApiClient;



if (mGoogleApiClient != null) {  mGoogleApiClient.registerConnectionCallbacks(this);            mGoogleApiClient.registerConnectionFailedListener`(this);
}

我希望这可以帮助你。

于 2016-03-17T20:03:53.737 回答