Android EventBus 的基本封装(二)

一、前言:

上一篇:Android EventBus 的基本使用(一)https://www.jianshu.com/p/c1e31b44d5d6

1. 简介:

EventBus是一款针对Android优化的发布/订阅事件总线。可以替代广播、startActivityForResultHandler、异步回调等来实现各组件间、组件与后台线程间的通信。它的优点是开销小,代码更优雅,以及将发送者和接收者解耦。

2. 使用场景:

通常我们在使用EventBus的时候都是直接需要接收通信的Activity/Fragment中通过EventBus.getDefault().register(this)订阅事件,在需要发起通信的逻辑直接调用EventBus.getDefault().post(Object event)来发布事件。但是要是一个项目中有很多地方都使用EventBus来通信,比如重新登录后更新各个页面的登录状态,或者是接收到通知更新消息提示等,都这样直接使用的话代码重复率很高,并且呢,如果以后升级或者更换EventBus时,各个地方都要修改,这就比较麻烦了。因此我一般是将EventBus的发布和订阅封装到BaseActivity/BaseFragment中。

3. 使用步骤:

  • 封装一个EventBus工具类,消息类MessageEvent
  • 在BaseActivity中选择注册及接收消息,默认不注册
  • 子Activity继承BaseActivity,如需接收消息,则重写父类的方法,返回true
  • 在需要发送消息的地方使用工具类发送消息(工具类也可以不封装,因为本身就一句话啊)

二、使用:

1.依赖:

//butterknife,配置下面 两行
implementation 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
//eventBus使用
implementation 'org.greenrobot:eventbus:3.1.1'

2. EventBusUtil类

public class EventBusUtil {
    /**
     * 订阅事件
     * @param subscriber
     */
    public static void register(Object subscriber) {
        EventBus.getDefault().register(subscriber);
    }

    /**
     * 取消订阅事件
     * @param subscriber
     */
    public static void unregister(Object subscriber) {
        //先检查一下
        if (EventBus.getDefault().isRegistered(subscriber)) {
            EventBus.getDefault().unregister(subscriber);
        }

    }

    /**
     * 发送消息
     * @param event
     */
    public static void sendEvent(Event event) {
        EventBus.getDefault().post(event);
    }

    /**
     * 发送粘性消息
     * @param event
     */
    public static void sendStickyEvent(Event event) {
        EventBus.getDefault().postSticky(event);
    }

}

封装一下EventBus的订阅、取消订阅、发布等方法:

3. 定义事件Event:

/**
 * Created by luo on 2019/7/17.
 * 定义发送消息的内容
 */

public class Event {

    private int code;
    private T data;

    public Event(int code) {
        this.code = code;
    }

    public Event(int code, T data) {
        this.code = code;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

EventCode类

public class EventCode {
    public static final int A = 0x111111;
    public static final int B = 0x222222;
    public static final int C = 0x333333;
    public static final int D = 0x444444;
}

通过泛型指定事件通信过程中的数据类型,code为事件码,使用的时候给不同的事件类型指定不同的code。

3. 定义BaseActivity:

所有的 Activity 继承BaseActivity。

public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //默认不注册,子类重写
        if (isRegisteredEventBus()) {
            //注册
            EventBusUtil.register(this);
        }

    }


    /**
     * 可以在子类中重写onStickyEventBusCome()
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(Event event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    /**
     * 可以在子类中重写onStickyEventBusCome()
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEventBusCome(Event event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(Event event) {

    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(Event event) {

    }


    /**
     * 是否注册事件分发
     *
     * 可以在子类中重写isRegisterEventBus()
     * @return true 注册;false 不注册,默认不注册
     */
    protected boolean isRegisteredEventBus() {
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //默认不注册,子类重写
        if (isRegisteredEventBus()) {
            //反注册
            EventBusUtil.unregister(this);
        }
    }
}

4. 在BaseActivity中选择注册及接收消息,默认不注册

public class MainActivity extends BaseActivity {

    private Button button1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        button1 = findViewById(R.id.button1);
        //点击事件
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TwoActivity.launch(MainActivity.this);
            }
        });
    }


    /**
     * 表示要注册事件
     *
     * @return
     */
    @Override
    protected boolean isRegisteredEventBus() {

        return true;
    }

    /**
     * 接受事件
     *
     * @param event
     */
    @Override
    public void onEventBusCome(Event event) {
        switch (event.getCode()) {
            case EventCode.A:
                Log.d("EventBus", "接收到A类型的Event");
                break;
            case EventCode.B:
                Log.d("EventBus", "接收到B类型的Event" + event.getData());
                break;
            case EventCode.C:
                User user = (User) event.getData();
                Log.d("EventBus", "接收到B类型的Event,携带User" + user);
                break;
            case EventCode.D:
                News news = (News) event.getData();
                Log.d("EventBus", "接收到D类型的Event,携带News" + news);
                break;
            default:
        }
    }
}

4. 发送EventBus信息:

 @OnClick({R.id.button1, R.id.button2, R.id.button3, R.id.button4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button1:
                EventBusUtil.sendEvent(new Event(EventCode.A));
                break;
            case R.id.button2:
                EventBusUtil.sendEvent(new Event(EventCode.B,"中国必将能够崛起!"));
                break;
            case R.id.button3:
                User user = new User();
                user.setName("孙海涛");
                user.setAge(29);
                Event event = new Event<>(EventCode.C, user);
                EventBusUtil.sendEvent(event);
                break;
            case R.id.button4:
                News news = new News();
                news.setMessage("这是一个重大的好消息啊");
                Event event2 = new Event<>(EventCode.D, news);
                EventBusUtil.sendEvent(event2);
                break;
            default:
        }
    }

三、总结:

  1. 在BaseActivity中选择注册及接收消息,默认不注册, 注册必须重写(在父类完成注册)isRegisteredEventBus()并且返回值为 true,接受消息方法必须重写onEventBusCome(Event event)
  2. 如果是 Fragment,可以写成 BaseFragemnt类,参考 Activity。
  3. 在Activity中发送事件,Activity只发送不需要接收Event的话就不注册,也不用复写isRegisterEventBus()和onEventBusCome(Event event)方法了。
  4. 将EventBus封装到BaseActivity/BaseFragment中,使得EventBus和项目解耦更加彻底,同时在需要使用的子Activity/Fragment中只需要复写isRegisterEventBus()和onEventBusCome(Event event)即可,不用每个地方都去订阅和取消订阅。并且给Event给定code和泛型能够很好的区分不同的事件来源和数据类型。

四、GitHub 地址

  • https://github.com/lyyRunning/MyEventBus

你可能感兴趣的:(Android EventBus 的基本封装(二))