NoLeakHandler各种版本

Leak:泄漏

public class NoLeakHandler extends Handler {
    private WeakReference<HandlerCallback> mCallback = new WeakReference<HandlerCallback>(null);
    private boolean isValid = true;

    public NoLeakHandler(HandlerCallback callback) {
        mCallback = new WeakReference<NoLeakHandler.HandlerCallback>(callback);
    }

    @Override
    public void handleMessage(Message msg) {
        if (mCallback.get() != null && isValid) {
            mCallback.get().handleMessage(msg);
        }
    }

    public interface HandlerCallback {
        public void handleMessage(Message msg);
    }

    public void setValid(boolean isValid) {
        this.isValid = isValid;
    }
}
public abstract class NoLeakHandler<T> extends Handler {  
    private WeakReference<T> mT;  

    public NoLeakHandler(T outClass) {  
        mT = new WeakReference<>(outClass);  
    }  

    @Override  
    public void handleMessage(Message msg) {  
        T t = mT.get();  
        handleMessage(msg, t);  
    }  

    public abstract void handleMessage(Message msg, T t);  
}
打赏