【EventBus】EventBus 事件总线框架简介 ( EventBus 使用流程 )
一、EventBus 事件总线框架简介
Android 中的事件传递机制 :
- 使用 Intent 在组件间传递信息 ;
- 使用 BroadcastReceiver 跨进程传递数据 ;
- 使用 Handler 跨线程通信 ;
- 使用 接口回调 机制 , Activity 与 Fragment 之间的通信方式 ;
EventBus 事件总线框架 简化了 Android 中的事件传递机制 ;
EventBus 常用于 组件 间的事件传递 , 实现了各个组件间的通信 , 如 Activity 与 Fragment 之间的通信 , Activity 与 Service 之间的通信 ;
EventBus GitHub 地址 : https://github.com/greenrobot/EventBus
EventBus 文档 : https://greenrobot.org/eventbus/documentation/
二、EventBus 使用流程
参考 https://github.com/greenrobot/EventBus 中的使用步骤 ;
1 . 导入 EventBus 依赖 ;
implementation 'org.greenrobot:eventbus:3.2.0'
  
 - 1
2 . 声明 EventBus 事件处理方法 ; 使用 @Subscribe 注解修饰处理消息的方法 , 该方法必须是 public void 修饰的 , 只有一个参数 , 参数类型随意 , 调用 EventBus.getDefault().post 即可发送消息到该方法进行处理 ;
    /**
     * 使用 @Subscribe 注解修饰处理消息的方法
     *      该方法必须是 public void 修饰的
     *      只有一个参数 , 参数类型随意
     *      调用 EventBus.getDefault().post 即可发送消息到该方法进行处理
     * @param msg
     */
    @Subscribe
    public void onMessgeEvent(String msg){
        textView.setText(msg);
    }
  
 - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
3 . 注册 EventBus , 一般在 onCreate 中注册 , 在 onDestory 中取消注册 ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 首先注册订阅 EventBus
        EventBus.getDefault().register(this);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册
        EventBus.getDefault().unregister(this);
    }
  
 - 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
4 . 发送消息 ; 调用 EventBus.getDefault().post 方法 , 将消息发送到消息处理方法中 ;
EventBus.getDefault().post("Hello EventBus !");
  
 - 1
文章来源: hanshuliang.blog.csdn.net,作者:韩曙亮,版权归原作者所有,如需转载,请联系作者。
原文链接:hanshuliang.blog.csdn.net/article/details/120426844
- 点赞
- 收藏
- 关注作者
 
             
           
评论(0)