android - Android如何依赖注入变量到非活动中?
问题描述
我有一个 android 应用程序,我想对一个不是活动或片段的类执行依赖注入,因此 applicationContext 不存在。
@HiltAndroidApp
class App: Application {
@Inject
lateinit var analytics: Analytics
override fun onCreate() {
super.onCreate()
// other details
}
}
我的应用模块
@Module
@InstallIn(ApplicationComponent::class)
abstract class AppModule() {
companion object {
@Provide
@Singleton
fun provideSomeClass(): SomeClass = SomeClass()
}
}
如果我尝试在活动中注入SomeClass它可以正常工作,但不能在非活动类上失败,并出现错误Object is not initialized。
class Consumer {
@lateinit var SomeClass someClass;
}
有人可以指出我做错了什么吗?
解决方案
注入非Activity类的字段
为此,您必须创建一个Interface
将成为 的@EntryPoint
,并将ApplicationContext
.
代码示例:
// No annotations here
class Consumer(ctx: Context) { // pass here the Android context
// Create an Interface (required by @InstallIn)
@EntryPoint
@InstallIn(SingletonComponent::class) // this could be implementation specific
interface Injector {
fun getSomeClass(): SomeClass // getter that will be injected
// you can also define a proper Kotlin Getter here
}
// create the injector object
val injector = EntryPoints.get(ctx, Injector::class.java)
// retrieve the injected object
val someObject = injector.getSomeClass()
suspend fun andFinallyUseIt() {
someObject.someMethod()
}
}
更多的:
- 确保你不缠绕你的范围
- 阅读更多:匕首@EntryPoint
推荐阅读
- python - 如何在 sam 本地环境中使用依赖项?
- javascript - JavaScript:使用 MediaRecorder 记录来自的流
- vtk - 如何在 VTK 中使用现有转换转换 Actor
- node.js - 如何在 Sequelize 中检索文件/图像
- reactjs - Redux + typescript:如何实现`injectReducer`?
- javascript - 未捕获的类型错误:无法读取未定义的属性“加密”
- python - 如何使用python自动更新谷歌大查询中的数据?
- android - 在 kotlin 的画布视图中添加一个按钮
- javascript - 如何在不暴露密码的情况下从 Firebase 发送电子邮件?
- python - Pysaprk 将复杂的 json 解析为行