Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating GoogleApiClient for multiple activities

I am developing an android app with Google+ API. I am having multiple activities which each require one instance of GoogleApiClient.

As I understand from this post it is possible to call the same instance of GoogleApiClient for each activity. My question is how do we create copies of the GoogleApiClient specifically?

Do we build one again with the .addApi(), .addscope() and implement onConnected method and OnConnectedFailedListener method again? Because it seems repetitive and inefficient. And wouldn't implementing these methods override the same methods from other activities too?

like image 665
orbital Avatar asked Jun 27 '14 15:06

orbital


People also ask

What can I use instead of GoogleApiClient?

Nested Class Summary Use GoogleApi based APIs instead. See Moving Past GoogleApiClient. This interface is deprecated. use GoogleApi based APIs instead.

What is GoogleApiClient?

The GoogleApiClient.Builder class provides methods that allow you to specify the Google APIs you want to use and your desired OAuth 2.0 scopes. Here is a code example that creates a GoogleApiClient instance that connects with the Google Drive service: GoogleApiClient mGoogleApiClient = new GoogleApiClient.


2 Answers

It's not expensive to create multiple instances of GoogleApiClient. In fact it will help with efficiency if you use more than just one API. Only the services you specifically request will be spooled up. So if one activity uses Plus and another uses Drive, the Plus service doesn't have to be spooled up when you're on the Drive activity.

To be clear, it is recommended that you create a separate instance of GoogleApiClient for each Activity, Fragment, Loader, Service, or Application that you create (maybe even some others that I forgot too).

If you really don't want to do that, use the application context instead of an activity or fragment to create the GoogleApiClient and hold a reference to it in an Application object.

like image 159
Hounshell Avatar answered Nov 09 '22 21:11

Hounshell


I have just had this same dilema. To get round this I used the BaseGameUtil... not sure if your using that but if you are then it is simple you can just have each activity extend the BaseGameActivity, add the required methods and then create a GoogleApiClient obj and getApiClient which will then give you the means to use the GoogleApiClient in your second activity.

mGoogleApiClient = getApiClient();

If your not using the BaseGameUtil then i think you would have to create it like you do above which is a pain, at least the basegameutil does it for you, plus you can always change whats in the BGU as they are more examples than libraries.

Hope this helps.

like image 1
Rob85 Avatar answered Nov 09 '22 20:11

Rob85