android开发——异步消息的处理(灵活的使用EventBus)

不知道EventBus如何使用的,可以看下这边博客:https://blog.csdn.net/river66/article/details/86571860

发送异步消息:

EventBus.getDefault().post(new AsyncMessage(200, "成功").setData(new Object()).sendTo("MainActivity"));

接收异步消息:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dealMessage(AsyncMessage.MainActivityMessage message) {
        switch (message.getCode()) {
            case 200:
                String message = message.getMessage();
                Object data = message.getData();
                break;
            case 404:
                break;
        }
    }

如何定义AsyncMessage 实体类呢?代码如下:

/**
 * @author dongxiaojiang
 * on 2019/4/22
 * 

* example: * 调用: EventBus.getDefault().post(new AsyncMessage(200,"message").setData("data").sendTo("MainActivity")); * 接收: function(AsyncMessage.MainActivityMessage message) */ public class AsyncMessage extends AbstractAsyncMessage { private Object data; private String targetActivityName; /** * 新增Activity异步消息类的时候,要新增此方法的case */ private Object getActivityMessage() { Object message = null; switch (targetActivityName) { case "MainActivity": message = new MainActivityMessage(this.getCode(), this.getMessage()); break; } return message; } /** * 新增Activity异步消息类的时候,继承ActivityMessage即可 */ public class MainActivityMessage extends ActivityMessage { public MainActivityMessage(int code, String message) { super(code, message); } } public AsyncMessage(int code) { super(code); } public AsyncMessage(int code, String message) { super(code, message); } public Object sendTo(String targetActivityName) { this.targetActivityName = targetActivityName; return getActivityMessage(); } public AsyncMessage setData(Object data) { this.data = data; return this; } @Override public Object getData() { return data; } public class ActivityMessage extends AbstractAsyncMessage { public ActivityMessage(int code, String message) { super(code, message); } @Override public Object getData() { return AsyncMessage.this.data; } } }

 AbstractAsyncMessage.java

/**
 * @author dongxiaojiang
 * on 2019/4/22
 */
public abstract class AbstractAsyncMessage {
    protected int code;
    protected String message;

    public abstract Object getData();

    public AbstractAsyncMessage(int code) {
        this(code, "");
    }

    public AbstractAsyncMessage(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {

        return code;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

如果对您有用的话赞一下呗!谢谢!

你可能感兴趣的:(进阶篇)