当前位置: 首页 > 工具软件 > EventBus > 使用案例 >

EventBus的封装

马寒
2023-12-01

最近来新公司,给了一个任务,引入eventbus,并进行封装。先上代码吧。

/**
 * Created by lizhiqinag on 18/05/15.
 * 使用说明:1、在接收eventbus事件的类中 重写isRegisterEventBus return true
 * protected boolean isRegisterEventBus() {
 *   return true;
 *}
 * 2、重写handleEvent处理事件
 *
 * @Subscribe(threadMode = ThreadMode.MAIN)
 * public void handleEvent(BaseEvent baseEvent) {//此处根据type 判断接收来自哪里的事件
 * if (baseEvent != null && "xxx".equals(baseEvent.type)){
 * Toast.makeText(this,baseEvent.content,Toast.LENGTH_SHORT).show();
 * }
 * }
 * 3、在任意位置发送事件
 * BaseEvent baseEvent = EventFactory.getInstance();
 * baseEvent.type = "xxx";
 * baseEvent.content = "ceshi";
 * EventBusUtils.post(baseEvent);
 */

public class EventBusUtils {

    public static void unregister(Object subscriber) {
        if (EventBus.getDefault().isRegistered(subscriber)) {
            EventBus.getDefault().unregister(subscriber);
        }
    }

    public static void register(Object subscriber) {
        EventBus.getDefault().register(subscriber);
    }

    public static void post(BaseEvent baseEvent) {
        EventBus.getDefault().post(baseEvent);
    }

    public static void postSticky(BaseEvent baseEvent) {
        EventBus.getDefault().postSticky(baseEvent);
    }
}

 

 

 

/**
 * Created by lizhiqiang on 18/5/16.
 * 所有eventbus event的基类
 */

public class BaseEvent {
    public String type;
    public String content;
    public Object object;
}

/**
 * Created by lizhiqiang on 2018/5/17.
 */

public class EventFactory {
    public static BaseEvent getInstance() {
        return new BaseEvent();
    }
}

在BaseActivity和BaseFagment中写入父类方法,用于子类重写

 
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册eventbus
        if (isRegisterEventBus()) {
            EventBusUtils.register(this);
        }
    }   
 @Override
    protected void onDestroy() {
        super.onDestroy();
        //解注册eventbus
        if (isRegisterEventBus()) {
            EventBusUtils.unregister(this);
        }
    }

    /**
     * 处理eventbus发过来的事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(BaseEvent baseEvent) {
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发,默认不绑定,子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

 

 

 

 

 

 

 

 类似资料: