EventBus集成和使用

来源:互联网 发布:去重sql语句 distinct 编辑:程序博客网 时间:2024/03/29 07:15

下载EventBus的类库
源码:https://github.com/greenrobot/EventBus

EventBus Demo和源码下载地址:http://download.csdn.net/detail/u011047066/9086161


一、搭建步骤:

1、将EventBus工程导入到ADT

2、工程引用EventBus项目(右键工程-->Properties-->Android-->Add-->选择EventBus项目-->点击“OK”)

二、使用说明(以activity之间传递数据为例):

1、在MainActivity中注册EventBus

[java] view plaincopy
  1. EventBus.getDefault().register(this);  

2、在接收消息界面定义函数来接收消息,一共有四种:onEventonEventMainThread、onEventBackgroundThreadThreadonEventAsync参数MyMsg为自定义的一个对象用来保存需要发送消息的内容

[java] view plaincopy
  1. public void onEventMainThread(MyMsg msg) {  
  2.         textTv.setText(msg.getMsg());  
  3.         Toast.makeText(MainActivity.this, msg.getMsg(), Toast.LENGTH_SHORT)  
  4.                 .show();  
  5.     }  

3、在发送消息界面通过EventBuspost()方法发送消息,参数MyMsg为自定义的一个对象用来保存需要发送消息的内容。

[java] view plaincopy
  1. EventBus.getDefault().post(new MyMsg("Event msg test"));  

4、在OnDestroy()方法中调用unregister()来移除注册

[java] view plaincopy
  1. @Override  
  2.     protected void onDestroy() {  
  3.         super.onDestroy();  
  4.         EventBus.getDefault().unregister(this);  
  5.     }  

三、用来接收消息的四个函数的不同:

onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackgroundThreadThread:如果使用onEventBackgroundThreadThread作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackgroundThreadThread就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackgroundThread函数直接在该子线程中执行。
onEventAsync使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.

在新线程发送消息:

pic1

在ui线程发送消息:

 pic2

四、接收消息的函数使用注意:

1、一个类中可以存在多个接收消息的函数,只要同名函数的参数类型不同即可,EventBuspost消息的后,接收消息端会根据参数类型调用对应接收消息的函数。

2、接收消息函数的访问权限必须是public,且只能有一个参数

否则程序会报异常:

Caused by: de.greenrobot.event.EventBusException: Subscriber class com.example.eventbustest.MainActivity 

has no public methods called onEvent

3、如果类中存在两个或多个参数相同的接收消息函数,则所有参数相同的函数都会被调用


参考:http://blog.csdn.net/harvic880925/article/details/40660137

0 0