主要功能:替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。
将Event添加到你的项目:
通过Gradle:
compile: "org.greenrobot:eventbus:3.0.0"
通过Maven:
<compile>
< groupId > org.greenrobot </ groupId >
< artifactId > eventbus </ artifactId >
< version > 3.0.0 </ version >
</ dependency >
基本使用:
1.自定义一个类(可以是空类)
public class AnyEventType {
public AnyEventType(){}
}
根据这个类,EventBus会判断,哪个函数传进去的参数是这个类的实例,就调用哪个。那如果有两个,那两个都会被调用!!!!
2.在要接受消息的页面注册
EventBus.getDefault().register(this);
3.发送消息
eventBus.post(new AnyEventType event);
4.接受消息的页面实现(共有四个函数,各功能不同,1.onEvent 2.onEventMainThread 3.onEventBackgroundThread 4.onEventAsync)
onEvent:发布事件和接受收事件在同一个线程中
onEventMainThread:无论发布事件在哪个线程中,接受事件onEventMainThread都会在UI线程中执行
onEventBackgroundThread 都会在子线程中运行
onEventAsync:无论事件在哪个线程中发布,都会创建一个新的子线程执行接受事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void getInfo(MyFirstEvent event){
String msg="接收到了消息"+event.getMsg();
Toast.makeText(this,msg, Toast.LENGTH_SHORT).show();
tv_show.setText(msg);
}
5.解除注册(onDestory())
eventBus.unregister(this);
将Event添加到你的项目:
通过Gradle:
compile: "org.greenrobot:eventbus:3.0.0"
通过Maven:
<compile>
< groupId > org.greenrobot </ groupId >
< artifactId > eventbus </ artifactId >
< version > 3.0.0 </ version >
</ dependency >
基本使用:
1.自定义一个类(可以是空类)
public class AnyEventType {
public AnyEventType(){}
}
根据这个类,EventBus会判断,哪个函数传进去的参数是这个类的实例,就调用哪个。那如果有两个,那两个都会被调用!!!!
2.在要接受消息的页面注册
EventBus.getDefault().register(this);
3.发送消息
eventBus.post(new AnyEventType event);
4.接受消息的页面实现(共有四个函数,各功能不同,1.onEvent 2.onEventMainThread 3.onEventBackgroundThread 4.onEventAsync)
onEvent:发布事件和接受收事件在同一个线程中
onEventMainThread:无论发布事件在哪个线程中,接受事件onEventMainThread都会在UI线程中执行
onEventBackgroundThread 都会在子线程中运行
onEventAsync:无论事件在哪个线程中发布,都会创建一个新的子线程执行接受事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void getInfo(MyFirstEvent event){
String msg="接收到了消息"+event.getMsg();
Toast.makeText(this,msg, Toast.LENGTH_SHORT).show();
tv_show.setText(msg);
}
5.解除注册(onDestory())
eventBus.unregister(this);