使用Hilt在BroadcastReceiver
内部进行依赖注入不起作用。我尝试使用来自BroadcastReceiver
的警报来调用MainActivity
,并且我正在获取UninitializedPropertyAccessException
。根据文档,它应该与向接收器添加@AndroidEntryPoint
注释一样简单,但不是。
示例代码:]
App.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
)
}
}
输出Logcat:
kotlin.UninitializedPropertyAccessException: lateinit property testHiltInjection has not been initialized
我认为目前尚不支持BroadcastReceiver。在https://dagger.dev/hilt/android-entry-point中说
注意:Hilt当前仅支持扩展ComponentActivity的活动和扩展androidx库Fragment的片段,而不支持Android平台中的(现已不推荐使用的)Fragment。
[内部运作方式:Hilt为@AndroidEntryPoint
带注释的组件(活动,片段,BroadcastReceiver等)创建抽象类,并且您的BroadcastReceiver在字节码转换中将生成的类扩展为基类。在基类onReceive
中,将注入对象。但是在生成的字节码类中,未调用超类onReceive
方法。这就是为什么不注入对象的原因。要测试,请在testHiltInjection()
类的HiltBroadcastReceiver
之前添加以下代码。顺便说一下,它仍然处于Alpha模式。
((HiltBroadcastReceiver_GeneratedInjector) BroadcastReceiverComponentManager.generatedComponent(context)).injectHiltBroadcastReceiver(UnsafeCasts.<HiltBroadcastReceiver>unsafeCast(this));