Search code examples
androidkotlinbroadcastreceiver

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


I have NotificationCenter object for interaction with 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")
        }
    }
}

Next I try to register receiver

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
)

And after that somewhere I do

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

But onReceive is not called. What am I doing wrong?


Solution

  • The class in which the BroadcastReceiver object is created must be initialized in onCreate().

    For example this object is created in class WebAuth(context: Context?) {}

    Wrong:

    class SettingsFragment : Fragment() {
    
        private var webAuth: WebAuth = WebAuth(context)
    
        // ...
    }
    

    Correct use:

    class SettingsFragment : Fragment() {
    
        private lateinit var webAuth: WebAuth
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            webAuth = WebAuth(context)
        }
    
        // ...
    }