android - 基于(API级别)条件使用@ContributesAndroidInjector

标签 android dagger-2

我有一个ServiceBinderModule在我的 Android 应用程序中,它负责添加我所有的 Service像这样的 DI 图:

@ContributesAndroidInjector
@ServiceScope
internal abstract fun myAutofillService(): MyAutofillService

我的问题是我有一个扩展 android.service.autofill.AutofillService 的服务仅可从 Android O 获取。在低于该 API 级别的设备上,我有不同的解决方案,但因为我有 MyAutofillService在图表中,应用程序在启动时崩溃( MyAutofillService 已经在 DaggerAppComponent 中,但 AutofillService 不存在于 Android 框架中)。

我看到了有关此主题的帖子:https://github.com/google/dagger/issues/1064

建议使用dagger.android.experimentalUseStringKeys@RequiresApi ,但它有一个警告:Keep in mind that enabling this also breaks incremental annotation processor support on Dagger 5.+ ,我认为这是一个破坏性的事情。我也不舒服把 experimental...填充到生产应用程序中。

有什么建议我可以做什么吗?我想把 MyAutofillService根据设备的 API 级别在图表上显示。

最佳答案

如果您不想使用experimentalUseStringKeys,我在该线程中喜欢的一个选项是 make a subcomponent for the higher API level 。该子组件只需包含 MyAutofillService 绑定(bind)。

@RequiresApi(Build.VERSION_CODES.O)
@Subcomponent(modules = [MyApi26Module::class])
interface MyApi26Subcomponent : AndroidInjector<MyApplication>

@RequiresApi(Build.VERSION_CODES.O)
@Module
abstract class MyApi26Module {
    @ContributesAndroidInjector
    @ServiceScope
    internal abstract fun myAutofillService(): MyAutofillService
}

创建主组件时,您可以检查 SDK_INT 来决定是直接安装它还是创建 MyApi26Subcomponent 并安装它。

关于android - 基于(API级别)条件使用@ContributesAndroidInjector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60615463/

相关文章:

android - Dagger 和数据绑定(bind)

android - 同一个项目中的 Realm.io/Dagger/Databinding

android - 工具 > Android 菜单在 Android Studio 中不存在

android - 在 Navigation Drawer Android 上添加 EditText

javascript - 在 Android Chrome 52 上使用 Web MIDI API

java - 在模块依赖中声明named的提供方法

android - 具有 Clean Architecture 的 MVP,在何处为网络操作添加线程

android - 是否可以使用 Android sdk 将短信保存在草稿中

android - 使用 Dagger2 提供不同的对象实例化

android - 何时调用 Dagger 2 inject in android component lifecycle