DialogFragment引起的内存泄露

3812次阅读  |  发布于4年以前

一、简介

DialogFragment是Android3.0之后引入的一种特殊的Fragment,官方建议使用DialogFragment代替Dialog或者AllertDialog来实现弹框的功能,因为它可以更好的管理Dialog的生命周期以及可以更好复用。

二、使用中遇到内存泄露

在使用过程中,由于业务需要对DialogFragment的dismiss事件进行了监听,在DialogFragment展示与消失的时候,经常会出现LeakCanary检测的内存泄露问题。查看LeakCanary的内存泄露引用链如下图所示:

这里只贴出了一张图,LeakCanary每次报出来的引用链并不完全相同,图上中显示的是RxJava的ThreadHandler,有的则显示的是高德地图的ThreadHandler(amapLocManagerThread),由此猜测这里并不是主线程的ThreadHandler引起的内存泄露,而是第三方库中的ThreadHandler引起的内存泄露。

但总的来说都是HandlerThread中处理的Message引用了NormalTitleBgDialog(DialogFragment)不能被释放。下面具体分析一下出现这个问题的原因。

三、原因分析

那么Message是怎么引用到DialogFragment的呢?在DialogFragment中搜索一下Message一无所获。DialogFragment实际是Dialog的封装,在Dialog中搜索Message试试,果然发现Dialog的Cancle和Dismiss都是通过Handler进行操作的,从这里入手分析一下内存泄露的原因:

Cancle和Dismiss的监听传入的是DialogFragment实现的两个接口:DialogInterface.OnCancelListener, DialogInterface.OnDismissListener

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mDialog.setOnCancelListener(this);
    mDialog.setOnDismissListener(this);
}

这里会通过mListenerHandler获取到一个mDismissMessage对象。

public void setOnDismissListener(@Nullable OnDismissListener listener) {
        if (mCancelAndDismissTaken != null) {
            throw new IllegalStateException(
                    "OnDismissListener is already taken by "
                    + mCancelAndDismissTaken + " and can not be replaced.");
        }
        if (listener != null) {
            mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);
        } else {
            mDismissMessage = null;
        }
    }

   public void setOnCancelListener(@Nullable OnCancelListener listener) {
        if (mCancelAndDismissTaken != null) {
            throw new IllegalStateException(
                    "OnCancelListener is already taken by "
                    + mCancelAndDismissTaken + " and can not be replaced.");
        }
        if (listener != null) {
            mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
        } else {
            mCancelMessage = null;
        }
    }

其中obtainMessage内部是通过Message.obtain方法得到,而这个方法会从消息池中通过复用的方式拿到Message。

public static Message obtain(Handler h, int what, Object obj) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.obj = obj;

        return m;
    }

 public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

至此,mDismissMessage中的obj属性引用了DialogFragment。但是Message是怎么被ThreadHandler引用到并且不能被释放的呢?下面看一下消息循环的处理过程是怎么样的。

3.Looper.loop

Looper.loop()方法在HandlerThread中运行。Looper.loop()方法执行过程就是消息的处理过程,首先从MessageQueue中取出一条消息,然后调用msg.target.dispatchMessage(msg)分发处理消息,最后调用msg.recycleUnchecked()回收消息。当MessageQueue中没有消息时queue.next()方法会阻塞线程。

public static void loop() {
        final Looper me = myLooper();
        final MessageQueue queue = me.mQueue;
        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
           msg.target.dispatchMessage(msg);//分发消息
            msg.recycleUnchecked();//回收消息
        }
    }

 void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = UID_NONE;
        workSourceUid = UID_NONE;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }

一些第三方库会创建自己的消息循环(HandlerThread),当这些消息循环(HandlerThread)中没有消息时,消息循环线程就会阻塞。从Java的内存模型我们知道线程开启时会创建自己独有的虚拟机栈空间,当消息循环发生阻塞时,方法中的局部变量不能被释放。

MessageQueue中取出的最后一条消息Message是Looper.loop()方法的局部变量,存储在栈帧的局部变量表中,由于当前线程被阻塞而不能被释放。以上我们知道了第三方库的HandlerThread会引用Message不能释放,但是第三方库的HandlerThread中的Message怎么会引用到DialogFragment呢?

由于内存泄露发生是在DialogFragment关闭时,我们看一下DialogFragment的dismiss是怎么处理的。

  1. dismiss()

Dialog关闭时也是通过发送消息来实现的,这里通过Message.obtain复制了一份mDismissMessage,同样是从消息池中复用的消息,因此这里是有可能取到已经回收的消息的。

private void sendDismissMessage() {
        if (mDismissMessage != null) {
            // Obtain a new message so this dialog can be re-used
            Message.obtain(mDismissMessage).sendToTarget();
        }
    }

当刚Dialog关闭dismiss时,刚好取出的是已经回收的消息,并且这条消息被另一个线程所引用,此时的mDimissMessage重新引用了DialogFragment,因此不能被回收,造成内存泄露。

总结:下图更容易说明造成内存泄露的原因。左图是线程A中的消息循环,线程A持有被回收到消息池中的消息对象,右边是主线程消息循环,Dialog关闭时从消息池中复用的的mDismissMessage被线程A持有,而mDismissMessage又持有DialogFragment,因为造成了内存泄露。

四、解决方案

override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        dialog.setOnCancelListener(null)
        dialog.setOnDismissListener(null)
    }

  public void setOnDismissListener(@Nullable OnDismissListener listener) {
        if (mCancelAndDismissTaken != null) {
            throw new IllegalStateException(
                    "OnDismissListener is already taken by "
                    + mCancelAndDismissTaken + " and can not be replaced.");
        }
        if (listener != null) {
            mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);
        } else {
            mDismissMessage = null;
        }
    }

直接拷贝DialogFragment代码至LeakDialogFragment类中,放弃实现DialogInterface.OnCancelListener, DialogInterface.OnDismissListener两个接口

public class LeakDialogFragment extends Fragment {

}

   public void onCancelDialog(DialogInterface dialog) {

    }

   public void onDismissDialog(DialogInterface dialog) {
        if (!mViewDestroyed) {
            // Note: we need to use allowStateLoss, because the dialog
            // dispatches this asynchronously so we can receive the call
            // after the activity is paused.  Worst case, when the user comes
            // back to the activity they see the dialog again.
            dismissInternal(true);
        }
    }
@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

  public void onDestroyView() {
        super.onDestroyView();
    }
public static class DialogDismissListener implements DialogInterface.OnDismissListener {
        private WeakReference<LeakDialogFragment> leakDialogFragmentWeakReference;

        public DialogDismissListener(LeakDialogFragment leakDialogFragment) {
            this.leakDialogFragmentWeakReference = new WeakReference<>(leakDialogFragment);
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            LeakDialogFragment leakDialogFragment = leakDialogFragmentWeakReference.get();
            if(leakDialogFragment!=null){
                leakDialogFragment.onDismissDialog(dialog);
            }
        }
    }

 public static class DialogCancleListener implements DialogInterface.OnCancelListener {
        private WeakReference<LeakDialogFragment> leakDialogFragmentWeakReference;

        public DialogCancleListener(LeakDialogFragment leakDialogFragment) {
            this.leakDialogFragmentWeakReference = new WeakReference<>(leakDialogFragment);
        }

        @Override
        public void onCancel(DialogInterface dialog) {
            LeakDialogFragment leakDialogFragment = leakDialogFragmentWeakReference.get();
            if(leakDialogFragment!=null){
                leakDialogFragment.onCancelDialog(dialog);
            }
        }
    }

在onActivityCreated中设置自定义的onDismissListener和onCancleListener,并且在onDestroyView时设置为空。

@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mDialogDissmissLitener = new DialogDismissListener(this);
        mDialog.setOnDismissListener(mDialogDissmissLitener);
        mDialogCancleListener = new DialogCancleListener(this);
        mDialog.setOnCancelListener(mDialogCancleListener);
    }

  public void onDestroyView() {
        super.onDestroyView();
        if(mDialogDissmissLitener!=null){
            mDialogDissmissLitener = null;
        }
        if(mDialogCancleListener!=null){
            mDialogCancleListener = null;
        }
    }

五、总结

本文从一个DialogFragment内存泄露问题出发,通过分析Dialog的Dismiss的监听实现方法,找出了引起内存泄露的原因。然后重写DialogFragment,通过静态内部类以及弱引用的方式来解决内存泄露问题,希望对于DialogFragment的使用有帮助。

参考:https://medium.com/square-corner-blog/a-small-leak-will-sink-a-great-ship-efbae00f9a0f

Copyright© 2013-2019

京ICP备2023019179号-2