为什么 onReceive 在我的 BroadcastReceiver 对象中不起作用? (科特林)

Why onReceive does not work in my BroadcastReceiver object? (Kotlin)

我有 NotificationCenter 用于与 BroadcastReceiver 交互的对象

object NotificationCenter {

    fun addObserver(
        context: Context?,
        notification: NotificationName,
        responseHandler: BroadcastReceiver?
    ) {
        if (context != null && responseHandler != null) {
            LocalBroadcastManager.getInstance(context)
                .registerReceiver(responseHandler, IntentFilter(notification.name))
        }
    }

    fun postNotification(
        context: Context?,
        notification: NotificationName,
        params: HashMap<String?, String?>
    ) {
        val intent = Intent(notification.name)
        for ((key, value) in params.entries) {
            intent.putExtra(key, value)
        }
        if (context != null) {
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
            Log.d("MyLog", "this log is printed")
        }
    }
}

接下来我尝试注册接收者

val responseReceiver: BroadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent) {

                Log.d("MyLog", "this log is not printed")
            }
}
NotificationCenter.addObserver(
    context, NotificationName.WebViewCookiesDidChange,
    responseReceiver
)

然后我在某个地方做

NotificationCenter.postNotification(
    context,
    NotificationName.WebViewCookiesDidChange,
    hashMapOf(
        NotificationKey.WebViewCookiesKey.name to cookies
    )
)

但是onReceive没有被调用。我做错了什么?

创建BroadcastReceiver对象的class必须在onCreate()中初始化

例如这个对象创建于class WebAuth(context: Context?) {}

错误:

class SettingsFragment : Fragment() {

    private var webAuth: WebAuth = WebAuth(context)

    // ...
}

正确使用:

class SettingsFragment : Fragment() {

    private lateinit var webAuth: WebAuth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        webAuth = WebAuth(context)
    }

    // ...
}