LeakCanary对话框片段泄漏检测

6

每次我尝试展示DialogFragment时都会出现内存泄漏。

这是我测试对话框的样子(取自安卓开发者页面):

public class TestDialog extends DialogFragment {

    public static TestDialog newInstance(int title) {
        TestDialog frag = new TestDialog();
        Bundle args = new Bundle();
        args.putInt("title", title);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int title = getArguments().getInt("title");

        return new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.ic_action_about)
                .setTitle(title)
                .setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //((FragmentAlertDialog)getActivity()).doPositiveClick();
                            }
                        }
                )
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                //((FragmentAlertDialog)getActivity()).doNegativeClick();
                            }
                        }
                )
                .create();
    }
}

我将其用以下代码启动,该代码在按钮按下时执行:

DialogFragment newFragment = TestDialog.newInstance(R.string.company_title);
newFragment.show(getFragmentManager(), "dialog");

以下是最好的部分: 输入图像描述

如何解决这个泄漏问题(或者至少隐藏它,因为canaryleak的所有通知都变得非常烦人)?


代码是否在您发布的可运行文件中?如果是,我认为您可以忽略这个问题。 - Uriel Frankel
我不确定我理解你的意思。这只是在按钮上设置点击监听器的常规操作。 - SMGhost
4个回答

4
这次泄漏的原因是由于DialogFragment的源代码:
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        ...
        // other codes
        ...
        mDialog.setCancelable(mCancelable);
        // hear is the main reason
        mDialog.setOnCancelListener(this);
        mDialog.setOnDismissListener(this);
        ...
        // other codes
        ...
    }

让我们来看看在函数 Dialog.SetOnCancelListener(DialogInterface.OnCancelListener) 中发生了什么:

/**
     * Set a listener to be invoked when the dialog is canceled.
     *
     * <p>This will only be invoked when the dialog is canceled.
     * Cancel events alone will not capture all ways that
     * the dialog might be dismissed. If the creator needs
     * to know when a dialog is dismissed in general, use
     * {@link #setOnDismissListener}.</p>
     * 
     * @param listener The {@link DialogInterface.OnCancelListener} to use.
     */
    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) {
            // here
            mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
        } else {
            mCancelMessage = null;
        }
    }

这里是Handler.obtainMessage(int, Object)的源代码:

    /**
     * 
     * Same as {@link #obtainMessage()}, except that it also sets the what and obj members 
     * of the returned Message.
     * 
     * @param what Value to assign to the returned Message.what field.
     * @param obj Value to assign to the returned Message.obj field.
     * @return A Message from the global message pool.
     */
    public final Message obtainMessage(int what, Object obj)
    {
        return Message.obtain(this, what, obj);
    }

最后,将调用函数Message.obtain(Handler, int, Object):

    /**
     * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>, and <em>obj</em>
     * members.
     * @param h  The <em>target</em> value to set.
     * @param what  The <em>what</em> value to set.
     * @param obj  The <em>object</em> method to set.
     * @return  A Message object from the global pool.
     */
    public static Message obtain(Handler h, int what, Object obj) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.obj = obj;

        return m;
    }

我们可以看到,cancelMessage 持有 DialogFragment 实例,这会导致内存泄漏。我只是想让你知道这一点,除了不使用 DialogFragment,我没有别的方法可以避免它。如果有更好的解决方案,请告诉我。

2

如果有人仍然遇到这个问题:我通过更新最新版本的leakcanary(目前为2.4)来解决了这个问题。看起来这是一个误报检测。我之前使用的是leakcanary 2.0beta-3。


0
我通过从自定义的DialogFragment实现中删除OnDismissListener和OnCancelListener来解决了这个泄漏问题。我还必须将null传递给负按钮侦听器:.setNegativeButton(R.string.cancel, null)

0
根据@EmMper的回答,如果您不需要onCancelListener,这是一个解决方法。
import android.app.Activity
import android.os.Bundle
import androidx.annotation.MainThread
import androidx.fragment.app.DialogFragment

open class PatchedDialogFragment : DialogFragment() {

    @MainThread
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        // Fixing the issue described here
        // https://dev59.com/2a_la4cB1Zd3GeqPv6O_
        val initialShowsDialog = showsDialog
        showsDialog = false
        super.onActivityCreated(savedInstanceState)
        showsDialog = initialShowsDialog

        if (!showsDialog) {
            return
        }
        val view = view
        if (view != null) {
            check(view.parent == null) { "DialogFragment can not be attached to a container view" }
            dialog!!.setContentView(view)
        }
        val activity: Activity? = activity
        if (activity != null) {
            dialog!!.ownerActivity = activity
        }
        dialog!!.setCancelable(isCancelable)
        if (savedInstanceState != null) {
            val dialogState =
                savedInstanceState.getBundle("android:savedDialogState")
            if (dialogState != null) {
                dialog!!.onRestoreInstanceState(dialogState)
            }
        }
    }
}

只需扩展PatchedDialogFragment而不是DialogFragment。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接