Android- Handler封装工具类

自定义封装Handle异步发送、接收消息工具类,使用仅需两行代码

public class BaseHandleMessage {
    private final ArrayList<Handler> mUpdateHandlers;
    private static BaseHandleMessage mInstance;
    public ArrayList<Handler> getmUpdateHandler() {
        return mUpdateHandlers;
    }
    private BaseHandleMessage() {
        mInstance = this;
        mUpdateHandlers = new ArrayList<>();
    }
    public synchronized static BaseHandleMessage getInstance() {
        if (mInstance == null)
            mInstance = new BaseHandleMessage();
        return mInstance;
    }
    public void addBaseHandleMessage(Handler handler) {
        if (handler != null) {
            mUpdateHandlers.add(handler);
        }
    }
    public void removeBaseHandleMessage(Handler handler) {
        if (handler != null) {
            mUpdateHandlers.remove(handler);
        }
    }
    public void setHandlerMessage(int what, Object objsect) {
        for (int i = 0; i < mUpdateHandlers.size(); i++) {
            Handler handler = mUpdateHandlers.get(i);
            Message msg = Message.obtain();
            msg.obj = objsect;
            msg.what = what;
            handler.sendMessage(msg);
        }
    }
    public void sendMessageDelayed(int what, Object objsect, long delayMillis) {
        for (int i = 0; i < mUpdateHandlers.size(); i++) {
            Handler handler = mUpdateHandlers.get(i);
            Message msg = Message.obtain();
            msg.obj = objsect;
            msg.what = what;
            handler.sendMessageDelayed(msg, delayMillis);
        }
    }
}
//发送Handler--->
BaseHandleMessage.getInstance().setHandlerMessage(int what, Object objsect);

//接收Handler--->
Handler handler = new Handler(message -> {
    if (message.what == WHAT) {
        //doing something()
    }
    return false;
});
BaseHandleMessage.getInstance().addBaseHandleMessage(handler);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值