EventBus使用优点:
方便简洁,发送和接收充分解耦。
AS添加依赖:
compile 'org.greenrobot:eventbus:3.1.1'
eventbus源码地址:https://github.com/greenrobot/EventBus
接下来说下EventBus的简单使用
在你的BaseActivity或者BaseFragment中注册
public class BaseActitvity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //注册 if (isRegEventBus()) { EventBusUtil.register(this); } } /** * 子类中是否需要注册 默认 false 不需要注册 * 如若需要子类实现 isRegEventBus() 方法 返回值改为true * * @return */ protected boolean isRegEventBus() { return false; } /** * 接受 发送事件 * * @param event */ @Subscribe(threadMode = ThreadMode.MAIN) public void onEventBus(Event event) { if (event != null) { recEvent(event); } } /** * 子类实现 接受事件方法 * * @param event */ protected void recEvent(Event event) { } /** * 接受粘性事件 方法 * * @param event */ @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onStickyEventBus(Event event) { if (event != null) { recStickyEvent(event); } } /** * 子类实现 接受粘性事件方法 * * @param event */ protected void recStickyEvent(Event event) { } @Override protected void onDestroy() { super.onDestroy(); //取消注册 if (isRegEventBus()) { EventBusUtil.unRegister(this); } } }
一、
从SecondActivity发送事件到Mainactivity流程:
MainActivity:
secondActivity发送事件到MainActivity:
在MainActivity中接收SecondActivity中发送的事件:
接收效果图:
二、Mainactivity发送粘性事件到SecondActivity
在secondActivity中接收粘性事件
/** * 点击事件 订阅 * @param view */ public void recStickyEvent(View view) { flag = true; if (flag) { EventBusUtil.register(this); flag = false; } }
接收效果图
完整代码参考github地址:https://github.com/h13520401236/EventBusDemo