【Android】EventBus使用相关

【Android】EventBus使用相关


EventBus的使用非常简单,主要使用到以下三个方法:

 //注册EventBus
    EventBus.getDefault().register(Object subscriber);
    //准备事件处理方法
    @Subscribe
    public void onEventXXX(Object event){
        //处理逻辑
    ...
    }
    //发送消息
    EventBus.getDefault().post(Object event);
    //注销EventBus
    EventBus.getDefault().unregister(Object subscriber);

注意在使用:

创建一个EventManager’管理类,在EventManager中判断需要注册事件的类中是否有相关的订阅方法

public static boolean isBindEventBus(Class clazz) {
    Method[] ms = clazz.getDeclaredMethods();
    for (Method m : ms) {
        if (m.isAnnotationPresent(Subscribe.class)) {
            return true;
        }
    }
    return false;
}

管理类代码:

public class EventManager {

    private static EventManager sInstance = new EventManager();
    private static EventBus mEventBus;

    private EventManager() {
        mEventBus = new CustomEventBus();
    }

    public static EventManager getsInstance() {
        return sInstance;
    }

    public void post(Object event) {
        mEventBus.post(event);
    }

    public void postSticky(Object event) {
        mEventBus.postSticky(event);
    }

    public void register(Object event) {
        mEventBus.register(event);
    }

    public void unRegister(Object event) {
        mEventBus.unregister(event);
    }

    /**
     * 判断需要注册事件的类中是否有相关的订阅方法
     *
     * @param clazz
     * @return
     */
    public static boolean isBindEventBus(Class clazz) {
        Method[] ms = clazz.getDeclaredMethods();
        for (Method m : ms) {
            if (m.isAnnotationPresent(Subscribe.class)) {
                return true;
            }
        }
        return false;
    }

    static final class CustomEventBus extends EventBus {
        @Override
        public void register(Object subscriber) {
            if (!isRegistered(subscriber)) {
                super.register(subscriber);
            }
        }
    }
}

你可能感兴趣的:(【Android】EventBus使用相关)