1. Add dependencies: compile 'org.greenrobot:eventbus:3.1.1'
2. Create a message class
3.
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate (savedInstanceState) setContentView(R.layout.activity_event_bus) EventBus.getDefault().register(this) btn_eventbus.onClick { startActivity<MainActivity>() } } override fun onDestroy() { super.onDestroy () EventBus.getDefault().unregister(this) } @Subscribe(threadMode = ThreadMode.MAIN) fun onMessageEvent(event: MessageEvent) { Toast.makeText(this,"test received event message", Toast.LENGTH_LONG) btn_eventbus.text = event.message Log.d("test", "test") }
The process is registration--->accept--->logout
Note that where you register, you need @Subscribe or will you report an error
4. Send information:
class EventPresent { fun sendMessage(){ println("================") EventBus.getDefault().post(MessageEvent("test event send")) } }
In this way, the Activity of EventBus can receive the information of the post
refer to: