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
}
});
複製程式碼