我已经开始使用 Dagger2 来管理依赖项,并且我试图了解如何使用 DI 来提供单例 GoogleApiClient。这样做的动机是:
-
减少样板代码:多个 Activity 和 Fragments 需要 GoogleApiClient
-
提高可测试性:目前这些 Activity 和 Fragments 尚未经过充分测试
我想在应用程序范围内提供一个单例 GoogleApiClient。
你如何处理回调?无论您选择一个自动管理或手动管理连接 https://developers.google.com/android/guides/api-client,有一些回调必须处理:
- GoogleApiClient.ConnectionCallbacks(仅限手动)
- GoogleApiClient.OnConnectionFailedListener(两者)
您可以使用注入来创建客户端
@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);
}
我希望这可以帮助你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)