EventBus

EventBus是一个Android端优化的publish/subscribe消息总线,简化了应用程序内各组件间、组件与后台线程间的通信。比如请求网络,等网络返回时通过Handler或Broadcast通知UI,两个Fragment之间需要通过Listener通信,这些需求都可以通过EventBus实现。
在EventBus中,使用约定来指定事件订阅者以简化使用。即所有事件订阅都都是以onEvent开头的函数,具体来说,函数的名字是onEvent,onEventMainThread,onEventBackgroundThread,onEventAsync这四个,这个和ThreadMode有关,有以下四个ThreadMode:

1.PostThread:事件的处理在和事件的发送在相同的进程,所以事件处理时间不应太长,不然影响事件的发送线程,而这个线程可能是UI线程。对应的函数名是onEvent。

2.MainThread: 事件的处理会在UI线程中执行。事件处理时间不能太长,这个不用说的,长了会ANR的,对应的函数名是onEventMainThread。

3.BackgroundThread:事件的处理会在一个后台线程中执行,对应的函数名是onEventBackgroundThread,虽然名字是BackgroundThread,事件处理是在后台线程,但事件处理时间还是不应该太长,因为如果发送事件的线程是后台线程,会直接执行事件,如果当前线程是UI线程,事件会被加到一个队列中,由一个线程依次处理这些事件,如果某个事件处理时间太长,会阻塞后面的事件的派发或处理。

4.Async:事件处理会在单独的线程中执行,主要用于在后台线程中执行耗时操作,每个事件会开启一个线程(有线程池),但最好限制线程的数目。
根据事件订阅都函数名称的不同,会使用不同的ThreadMode,比如果在后台线程加载了数据想在UI线程显示,订阅者只需把函数命名为onEventMainThread。

可以在任意线程任意位置发送事件,直接调用EventBus的post(Object)方法,可以自己实例化EventBus对象,但一般使用默认的单例就好了:EventBus.getDefault(),根据post函数参数的类型,会自动调用订阅相应类型事件的函数。


EventBus的基本使用步骤:
1.定义事件类型:
这个事件类型可以是任意类型的对象
public class ResultBeen {
private int result;
private String response;

public ResultBeen(String response) {
this.response =response;
}

public int getResult() {
return result;
}

public void setResult(int result) {
this.result = result;
}

public String getResponse() {
return response;
}

@Override
public String toString() {
return response;
}
}

2.定义事件处理方法:
public void onEventMainThread(ResultBeen event) {
this.tv_result.setText(event.getResponse());
}

3.注册订阅者
通过EventBus.getDefault().register方法可以向EventBus注册来订阅事件
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

4.发送事件:
直接调用EventBus.getDefault().post(Event)就可以发送事件,根据Event的类型就可以发送到相应事件的订阅者。
public void fetchBaidu(Context context) {
RequestQueue mRequestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://www.baidu.com", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
EventBus.getDefault().post(new ResultBeen(response));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
EventBus.getDefault().post(new ResultBeen(error.getMessage()));

}
});

mRequestQueue.add(stringRequest);
}

5.取消注册:
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值