Search code examples
androidbroadcastreceiver

Why dynamic registered standard Broadcast in Android cannot be received?


My code in a fragment: `private var logoutReceiver: BroadcastReceiver? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    logoutReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            LogUtils.d("action--->")
        }
    }


    val filter = IntentFilter()
    filter.addAction("com.example.broadcast.MY_NOTIFICATION")
    requireContext().registerReceiver(logoutReceiver!!, filter)
    LogUtils.d("register")

    Handler().postDelayed({
        Intent().let {
            it.action = "com.example.broadcast.MY_NOTIFICATION"
            requireContext().sendBroadcast(it)
            LogUtils.i("send")
        }
    }, 2000)
}

override fun onDestroy() {
    super.onDestroy()
    if (logoutReceiver != null) {
        requireContext().unregisterReceiver(logoutReceiver!!)
        LogUtils.e("unregister")
    }

}`

The problem is onReceive() didn't called, but when I replace requireContext() with LocalBroadcastManager, it worked well, the compileSdkVersion is 33, is there any permissions I need to add in a new compileSdkVersion?

I replace requireContext() with LocalBroadcastManager, it worked well


Solution

    • My Solution

    I found a solution, register the BoradcastReceiver both in AndroidManifest.xml and Fragment/Activity at the same time, and it worked.

    • Attention

    As we konwn, after Android 8, when sending a broadcast, the intent.setClass(context,Class.forName("xxx")) is neccessary, but if we register the BroadcastReceiver in a Fragment at the same time, the setClass clause can be removed.

    • What's the reason?

    I think that's because Google changed its policy in a certain version of sdk that we must register our broadcast receiver in AndroidManifest.xml even if we only want to register it in a Fragment or an Activity, by I don't know why they refuse to tell developers this policy change in their official website.