我有一个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/