所以我有一个要注入BroadcastReceiver的类。
这是课程:
class SomeClass @Inject contructor(@ActivityContext private val ctx: Context){
fun doStuff(){...}
}
尝试此操作时出现以下错误:error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ActivityContext android.content.Context cannot be provided without an @Provides-annotated method.
@AndroidEntryPoint
class Broadcast: BroadcastReceiver() {
@Inject lateinit var someClass: SomeClass
override fun onReceive(context: Context?, intent: Intent?) {
someClass.doStuff()
}
}
我认为SomeClass
的上下文存在问题,因为我尝试过删除该参数,但它可以正常工作。
答案 0 :(得分:0)
用@ActivityContext
注释的类只能注入到@ActivityScoped
的对象内部。所以是的,您是对的,context
是这里的问题。
答案 1 :(得分:0)
@ActivityContext
仅可用于活动生命周期,而不能使用@ApplicationContext
。
class SomeClass @Inject contructor(@ApplicationContext private val ctx: Context){
}
答案 2 :(得分:0)
创建此类:
/**
* This class is created in order to be able to @Inject variables into Broadcast Receiver.
* Simply Inherit this class into whatever BroadcastReceiver you need and freely use Dagger-Hilt after.
*/
abstract class HiltBroadcastReceiver : BroadcastReceiver() {
@CallSuper
override fun onReceive(context: Context, intent: Intent?) {
}
}
然后,您的BroadcastReceiver
应该如下所示:
@AndroidEntryPoint
class BootReceiver : HiltBroadcastReceiver() {
// Injection -> Example from my application
@Inject
lateinit var internetDaysLeftAlarm: InternetDaysLeftAlarm
override fun onReceive(context: Context, intent: Intent?) {
super.onReceive(context, intent)
// Do whatever you need
}
}
另外,正如某些人在此已经提到的,请注意@ActivityContext
。相反,您应该只使用@ApplicationContext