我已经开始使用 Dagger2 来管理依赖项,并且我正在尝试了解如何使用 DI 来提供单例 GoogleApiClient。这样做的动机是:
- 减少样板代码:多个 Activity 和 Fragments 需要 GoogleApiClient
- 提高可测试性:目前这些 Activity 和 Fragment 尚未经过充分测试
我想在应用程序范围内提供一个单例 GoogleApiClient。
您如何处理回调?您是否选择 auto-managed or manually-managed connection ,有一些回调必须处理:
- GoogleApiClient.ConnectionCallbacks(仅限手动)
- GoogleApiClient.OnConnectionFailedListener(两者)
最佳答案
您可以使用注入(inject)来创建客户端
@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);
}
希望这对您有帮助。
关于dagger-2 - 如何为 Dagger2 提供 GoogleApiClient 依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35972868/