弱引用Handler

Handler 导致内存泄漏问题很常见,因此需要让它弱引用 context。每次都写在调用处明显不可能,如下处理一下更好用。

  • 消息处理回调接口
public interface IMessageConsumer {
    //消费事件
    void handleMessage(Message msg);
}
  • 弱引用包装
public class WeakHandler extends Handler {

    private final WeakReference consumerWeakReference;

    public WeakHandler(IMessageConsumer consumer) {
        consumerWeakReference = new WeakReference<>(consumer);
    }

    @Override
    public void handleMessage(Message msg) {
        IMessageConsumer consumer = consumerWeakReference.get();
        if (consumer != null) {
            consumer.handleMessage(msg);
        }
    }
}

你可能感兴趣的:(Android,弱引用)