我该如何将需要上下文的类注入到Broadcast Receiver中?

时间:2020-11-08 21:11:45

标签: android kotlin dagger-hilt

所以我有一个要注入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的上下文存在问题,因为我尝试过删除该参数,但它可以正常工作。

3 个答案:

答案 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