使用 Hilt内部的依赖注入BroadcastReceiver
不起作用。我尝试BroadcastReceiver
使用警报调用 aMainActivity
并且我得到了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