本文介绍了为多个活动创建GoogleApiClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有Google+ API的Android应用程序。我有多个活动,每个活动需要一个GoogleApiClient实例。

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

据我所知,可以为每个活动调用同一个GoogleApiClient实例。我的问题是我们如何特别创建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?

我们是否使用.addApi(),.addscope()再次构建一个并实现onConnected方法和OnConnectedFailedListener方法呢?因为它似乎重复性和低效率。并不会实现这些方法覆盖从其他活动相同的方法?

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?

推荐答案

创建多个 GoogleApiClient 。事实上,如果您使用的不仅仅是一个API,它将有助于提高效率。只有您特别要求的服务才会被注册。因此,如果一个活动使用Plus,另一个使用Drive,则在进行Drive活动时,不必将Plus服务假脱机。

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.

建议您为您创建的每个Activity,Fragment,Loader,Service或Application创建一个单独的 GoogleApiClient 实例(可能甚至还有一些我也已经忘记了)。

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).

如果您真的不想这样做,请使用应用程序上下文而不是活动或片段来创建 GoogleApiClient 并在Application对象中保存对它的引用。

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.

这篇关于为多个活动创建GoogleApiClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 08:47