简体   繁体   中英

android EventBus as LocalBroadcastManager replacement

greenrobot EventBus has been suggested as replacement of (now deprecated) LocalBroadcastManager. I'm current using LocalBroadcastManager to send intents from service to MainActivity like this:

val intent = Intent("service event")
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
intent.putExtra("param", "some value")
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)

That clears the stack and MainActivity becomes visible as the only activity in the stack.

How can I achieve the same ( Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP ) effect when posting EventBus event?

After some experiments, I found a "solution":

  1. Register EventBus in onCreate() of MainActivity EventBus.getDefault().register(this) . That makes it possible for MainActivity to receive posts even when it is not on top of the activity stack. Then, of course, unregister in onDestroy() .
  2. In MainActivity event receiver function, start MainActivity again with Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP flags, for example like this:
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onEventReceived(event: BusEvent) {
        val i = Intent(applicationContext, MainActivity::class.java)
        i.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
        i.putExtra("action", event.action)
        i.putExtra("params", event.params)
        startActivity(i)
    }

I'm new to this and better solutions are appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM