Reputation: 439
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?
Upvotes: 0
Views: 1393
Reputation: 439
After some experiments, I found a "solution":
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()
.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.
Upvotes: 1