在进行Android开发时,当涉及大量组件之间的通信,使用Intent、Handler、Broadcast进行模块间通信、模块与后台线程进行通信时,代码量大,而且高度耦合。EventBus简化了应用程序内各个组件之间进行通信的复杂度,尤其是碎片之间进行通信的问题,可以避免由于使用广播通信而带来的诸多不便。(github地址:EventBus)
EventBus3.0有四种线程模型,分别是:
implementation("org.greenrobot:eventbus:3.3.1")
定义一个事件的封装对象。在程序内部就使用该对象作为通信的信息:
public class AsnDetailEventBus {
private String asnCode;
private String lotNo;
private String ItemCode;
private String ItemName;
private String packageUnit;
private String status;
private String sortCategory;
private String planQty;
private String receiveQty;
private String putawayQty;
public String getAsnCode() {
return asnCode;
}
public void setAsnCode(String asnCode) {
this.asnCode = asnCode;
}
public String getLotNo() {
return lotNo;
}
public void setLotNo(String lotNo) {
this.lotNo = lotNo;
}
public String getItemCode() {
return ItemCode;
}
public void setItemCode(String itemCode) {
ItemCode = itemCode;
}
public String getItemName() {
return ItemName;
}
public void setItemName(String itemName) {
ItemName = itemName;
}
public String getPackageUnit() {
return packageUnit;
}
public void setPackageUnit(String packageUnit) {
this.packageUnit = packageUnit;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSortCategory() {
return sortCategory;
}
public void setSortCategory(String sortCategory) {
this.sortCategory = sortCategory;
}
public String getPlanQty() {
return planQty;
}
public void setPlanQty(String planQty) {
this.planQty = planQty;
}
public String getReceiveQty() {
return receiveQty;
}
public void setReceiveQty(String receiveQty) {
this.receiveQty = receiveQty;
}
public String getPutawayQty() {
return putawayQty;
}
public void setPutawayQty(String putawayQty) {
this.putawayQty = putawayQty;
}
public AsnDetailEventBus(String asnCode, String lotNo, String itemCode, String itemName, String packageUnit, String status, String sortCategory, String planQty, String receiveQty, String putawayQty) {
this.asnCode = asnCode;
this.lotNo = lotNo;
ItemCode = itemCode;
ItemName = itemName;
this.packageUnit = packageUnit;
this.status = status;
this.sortCategory = sortCategory;
this.planQty = planQty;
this.receiveQty = receiveQty;
this.putawayQty = putawayQty;
}
}
在Activity或者Fragment里订阅事件时,注册EventBus。一般选择在Activity的onCreate()方法里去注册EventBus,在onDestory()方法里,去解除注册。
注册事件
// 注册事件
EventBus.getDefault().register(this);
解除注册
@Override
public void onDestroy() {
//移除所有粘性事件
EventBus.getDefault().removeAllStickyEvents();
//解除注册
EventBus.getDefault().unregister(this);
super.onDestroy();
}
// 发布粘性事件
EventBus.getDefault().postSticky(asnDetailEventBus )
// 发布普通事件
EventBus.getDefault().post(messageEvent);
//处理黏性事件
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void StickyEventBus(AsnDetailEventBus event){
//TODO
}
//处理普通事件
@Subscribe(threadMode = ThreadMode.MAIN)
public void eventBus(AsnDetailEventBus event) {
//TODO
}
所谓粘性事件,就是在发送事件之后再订阅该事件也能收到该事件。请注意这里与普通事件的区别,普通事件是先注册在绑定。