EventBus Usage
16lz
2021-12-04
EventBus is a publish/subscribe event bus optimized for Android.
so make it simple,just think EventBus as a framework that allow different compoents to communicate,
usually a subscribe register a certain event,then whenever a publisher has post an event,any subscribes who had register this event will be able to receive the notify.
This is an example,Let's say MainActivity is a subscribe who has register to receive RecvEvent event,
And Second Activity is a publicer who will post a RecvEvent when his btn is clicked.Theoretically speaking,MainActivity is able to recevie the event that posted by SecondActivity.
//From above,we know that EventBus contains three objects:Event,Subscribe,Publisher
//Eventpublic class RecvEvent{private final String info;public RecvEvent(String info){ this.info = info;}public String getInfo(){return info;}}//Subscribe:MainActivitypublic class MainActivity extends AppCompatActivity { private TextView tvShowInfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvShowInfo = (TextView)findViewById(R.id.tvShowRecv);//register to recevie ShowRecvEvent event EventBus.getDefault().register(this); } @Override protected void onDestroy() { super.onDestroy();//destroy res EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onRecvEvent(ShowRecvEvent event) { tvShowInfo.setText(event.getInfo()); } public void onJump(View view) { startActivity(new Intent(this,SecondActivity.class)); }}//publisher:SecondActivitypublic class SecondActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); } public void onSend(View view) { EventBus.getDefault().post(new ShowRecvEvent("this is from second activity")); }}
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer