我怎样才能将需要上下文的 class 注入到带有刀柄的广播接收器中?

How can i inject a class that needs context into Broadcast Receiver with hilt?

所以我有一个 class 我想注入 BroadcastReceiver。

这是class:

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 的上下文有问题,因为我尝试删除该参数并且它有效。

@ActivityContext 注释的

类 只能注入到 @ActivityScoped 的对象内部。所以是的,你是对的,context 是这里的问题。

@ActivityContext 只能在 Activity 生命周期中使用,但您可以使用 @ApplicationContext.

而不是这个
class SomeClass @Inject contructor(@ApplicationContext private val ctx: Context){
}

创建这个 class:

/**
 * 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