如何通过Dagger2提供GoogleApiClient依赖关系? [英] How do you provide a GoogleApiClient dependency with Dagger2?

查看:106
本文介绍了如何通过Dagger2提供GoogleApiClient依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用Dagger2来管理依赖关系,并且试图了解如何使用DI提供单例GoogleApiClient。这样做的动机是:

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:


  • 减少样板代码:多个活动和片段需要GoogleApiClient

  • 提高可测试性:目前,这些活动和片段尚未得到很好的测试

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

我想在Application范围内提供Singleton GoogleApiClient。

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(仅手动)

  • GoogleApiClient.OnConnectionFailedListener(两者)

推荐答案

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

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();
        }

然后管理您活动的回调

@Inject GoogleApiClient mGoogleApiClient;



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

我希望这会对您有所帮助。

I hope this might help you.

这篇关于如何通过Dagger2提供GoogleApiClient依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆