美文网首页
Handler使用弱引用优化

Handler使用弱引用优化

作者: 小婷android | 来源:发表于2021-03-30 14:18 被阅读0次
    定义一个DefaultHandler类
    public abstract class DefaultHandler<T> extends Handler {
    
        protected final WeakReference<Fragment> mReference;
        protected final WeakReference<T> mReferenceT;
    
        public DefaultHandler(Fragment context, T t) {
            mReference = new WeakReference<>(context);
            mReferenceT = new WeakReference<>(t);
        }
    
        @Override
        public final void handleMessage(Message msg) {
            super.handleMessage(msg);
            Fragment context = mReference.get();
            if (context != null) {
                if (context instanceof Fragment && ((Activity) context.getActivity()).isFinishing()) {
                    removeCallbacksAndMessages();
                } else {
                    T t = mReferenceT.get();
                    if (t != null) {
                        this.handleMessage(msg, t);
                    } else {
                    }
                }
            } else {
                removeCallbacksAndMessages();
            }
        }
    
        public abstract void handleMessage(Message msg, T t);
    
        public void removeCallbacksAndMessages() {
            removeCallbacksAndMessages(null);
            mReference.clear();
            mReferenceT.clear();
        }
    
    }
    
    在fragmeng中引用
    private VerifyHandler handler = new VerifyHandler(this, this);
    
        private static class VerifyHandler extends DefaultHandler<WellControlMonitorFragment> {
            public VerifyHandler(WellControlMonitorFragment context, WellControlMonitorFragment fragment) {
                super(context, fragment);
            }
    
            @Override
            public void handleMessage(Message msg, WellControlMonitorFragment fragment) {
                if (msg.obj instanceof RunControlInfo) {
                    RunControlInfo controlInfo = (RunControlInfo) msg.obj;
                    fragment.showCurrentData(controlInfo.getTnm(), controlInfo.getVal() + "");
                } else {
                    for (int i = 0; i < fragment.tempData.getData().getData().size(); i++) {
                        fragment.showCurrentData(fragment.tempData.getData().getData().get(i).getTnm(), fragment.tempData.getData().getData().get(i).getVal() + "");
                    }
                }
            }
        }
    
           Message msg = Message.obtain();
                msg.obj = runControlInfo;
                handler.sendMessage(msg);
    

    相关文章

      网友评论

          本文标题:Handler使用弱引用优化

          本文链接:https://www.haomeiwen.com/subject/asfghltx.html