gpt4 book ai didi

android - Hilt 注入(inject)不适用于 BroadcastReceiver

转载 作者:行者123 更新时间:2023-12-04 11:09:39 33 4
gpt4 key购买 nike

BroadcastReceiver 内部的依赖注入(inject)使用 Hilt 不起作用。我尝试调用 BroadcastReceiver使用来自 MainActivity 的警报我得到UninitializedPropertyAccessException .根据文档,它应该像添加 @AndroidEntryPoint 一样简单对接收者的注释,但不是。
示例代码:
应用.kt:

@HiltAndroidApp
class App: Application() {
override fun onCreate() {
super.onCreate()
Log.d(App::class.simpleName, "onCreate: Application")
}
}
TestHiltInjection.kt:
class TestHiltInjection @Inject constructor() {

operator fun invoke() {
Log.d(TestHiltInjection::class.java.simpleName, "invoke called.")
}
}
HiltBroadcastReceiver.kt:
@AndroidEntryPoint
class HiltBroadcastReceiver : BroadcastReceiver() {

@Inject lateinit var testHiltInjection: TestHiltInjection

override fun onReceive(context: Context?, intent: Intent?) {
testHiltInjection()
}
}
MainActivity.kt:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

val pending = PendingIntent
.getBroadcast(this, 0, Intent(this, HiltBroadcastReceiver::class.java), 0)
manager.setInexactRepeating(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
15000, 15000,
pending
)
}
}
输出日志猫:
kotlin.UninitializedPropertyAccessException: lateinit property testHiltInjection has not been initialized
更新
问题已经在 2.29.1 版本解决,使用 @AndroidEntryPoint

最佳答案

更新:根据issue该问题应在版本 2.29.1 中修复 Dagger 柄。因此,只需使用版本 2.29.1-alpha或以上。不要忘记更新hilt-android-gradle-plugin版本 as well .

原答案:有一个 GitHub issueworkaround .似乎注入(inject)不起作用,因为它实际上发生在 onReceive() 内部。生成的父类的方法。问题是你不能调用 super 方法,因为它是抽象的。但是你可以创建一个简单的包装类来解决这个问题:

abstract class HiltBroadcastReceiver : BroadcastReceiver() {
@CallSuper
override fun onReceive(context: Context, intent: Intent) {}
}

@AndroidEntryPoint
class MyBroadcastReceiver : HiltBroadcastReceiver() {
@Inject lateinit var testHiltInjection: TestHiltInjection

override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent) // <-- it's the trick

...
}
}

关于android - Hilt 注入(inject)不适用于 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62335727/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com