How do you provide a GoogleApiClient dependency with Dagger2?
Asked Answered
C

1

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)
Credulity answered 13/3, 2016 at 16:42 Comment(0)
S
7

You can use the injection to create the client

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

And then manage the call backs on your activity

@Inject GoogleApiClient mGoogleApiClient;



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

I hope this might help you.

Stannum answered 17/3, 2016 at 20:3 Comment(5)
Are onResume() and onPause() the correct place to register/unregister the listener?Credulity
Your example provider method creates the client (not just the builder, as your wording suggests).Credulity
@Credulity Yes you are right, it provides the client. The disconnect is normally is called on onStop() and onStart you can call connectStannum
Just want to add that if you wont to avoid boilerplate onStart/onStop you can just pass lifecycle ApiClient wrapper and let handle it there.Vivanvivarium
I am getting googleApiClient is not initialized, any ideas?Spinney

© 2022 - 2024 — McMap. All rights reserved.