EventBus的使用以及原理

来源:互联网 发布:php按值删除数组元素 编辑:程序博客网 时间:2024/05/22 01:29
1、eventbus用途
  eventbus是一个用于Activity,Fragment、Service、Threads之间信息传递的一个发布/订阅事件集。
(1)解决问题:
    传统android组件之间的通信方式有:Activity之间使用Intent、Serivce与Activity之间使用的Broadcast;Fragment和Activity之间互相持有对方的引用,通过调用对方相关的方法进行事件传递。
     传递事件的问题在于:通信方式没有实现解耦,是硬编码在组件中的。组件一旦发生改变,对应的通信方式就需要跟着改变。
     (2)优势 
      简化组件之间的通信方式
2、eventbus的使用
(1)
as引入:
compile 'org.greenrobot:eventbus:3.0.0'  
provided 'org.glassfish:javax.annotation:10.0-b28' //解决获取不到@Subscribe注解的问题  
eclipse:导入jar包
(2)定义事件
publicclassSearchAddressEvent {
     publicfinalstaticintSEARCH_SCHOOL= 1;
     publicfinalstaticintSEARCH_HOME= 2;
     
     
     publicIntegertype;
     publicStringid;
     publicStringname;
     publicStringaddress;
     publicStringlocation;
     publicSearchAddressEvent(inttype,String id,String name,String address,String location) {
           this.type= type;
           this.id= id;
           this.name= name;
           this.address= address;
           this.location= location;
     } 
     
}
(3)注册EventBus
一般在onCreate中
 EventBus.getDefault().register(this);
在onDestory中
EventBus.getDefault().unregister(this);
处理事件四种方式
public void onEvent(PostEvent event) {}  
使用onEvent来接收事件,那么接收事件和分发事件在一个线程中执行 
 public void onEventMainThread(MainEvent event)  {} 
用onEventMainThread来接收事件,那么不论分发事件在哪个线程运行,接收事件永远在UI线程执行,
public void onEventBackgroundThread(BackEvent event)  {}
使用onEventBackgroundThread来接收事件,如果分发事件在子线程运行,那么接收在同样线程运行,如果分发事件在UI线程,那么会启动一个子线程运行接收事件 
public void onEventAsync(AsyncEvent event)  {} 
使用onEventAsync接收事件,无论分发事件在(UI或者子线程)哪个线程执行,接收都会在另外一个子线程执行 
(4)发布事件Post
EventBus.getDefault().post(new SearchAddressEvent (1, "id","name","address","location"));  
3、源码分析(个人理解)
(1)首先注册事件,注册时通过反射找到此类的所有的已onEvent开头的方法
(2)找到所有方法后,通过方法获取到订阅的类型,添加到订阅者中
(3)Post时,通过Post的类找到所有订阅此类的类。执行订阅的方法


参考博客:
http://blog.csdn.net/fengqiaoyebo2008/article/details/43055251
http://blog.csdn.net/evan_man/article/details/51328628






0 0
原创粉丝点击