Handler的泄露处理:
public class BaseHandler<T> extends Handler {
WeakReference<T> wr; //弱引用
BaseHandler.BaseHandlerCallBack callBack;
public BaseHandler(T t,BaseHandler.BaseHandlerCallBack callBack){
wr = new WeakReference<T>(t);
AppLog.LOGE("Handler0:" + t);
AppLog.LOGE("Handler1:" + wr);
this.callBack = callBack;
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
T t = wr.get();//如果此方法为空, 那么说明wr指向的对象已经被回收了.
AppLog.LOGE("Handler:" + t);
if(t != null){
callBack.callBack(msg);
}
}
public interface BaseHandlerCallBack {
/**
* 提供的BaseHandler的callback返回接口
* @param msg 传递的Message信息
*/
void callBack(Message msg);
}
}
引用:
private Handler handler = new BaseHandler<>(UpLoadService.class, new BaseHandler.BaseHandlerCallBack() {
@Override
public void callBack(Message msg) {
//do something
}
});