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指向的對(duì)象已經(jīng)被回收了.
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
}
});