定义一个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);
网友评论