首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LeakCanary DialogFragment泄漏检测

LeakCanary DialogFragment泄漏检测
EN

Stack Overflow用户
提问于 2018-11-07 15:33:19
回答 4查看 1.5K关注 0票数 5

每次我尝试显示DialogFragment时,我都会遇到内存泄漏。

下面是我的测试对话框(取自android开发者页面):

代码语言:javascript
复制
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();
    }
}

我使用以下代码启动它,这些代码在按下按钮时执行:

代码语言:javascript
复制
DialogFragment newFragment = TestDialog.newInstance(R.string.company_title);
newFragment.show(getFragmentManager(), "dialog");

下面是最精彩的部分:

如何解决这个漏洞(或者至少隐藏它,因为canaryleak对所有这些通知都变得非常恼人)?

EN

回答 4

Stack Overflow用户

发布于 2020-02-06 18:59:31

造成这次泄漏的原因是DialogFragment的源代码

代码语言:javascript
复制
@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)中发生了什么

代码语言:javascript
复制
/**
     * 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)的源代码

代码语言:javascript
复制
    /**
     * 
     * 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)

代码语言:javascript
复制
    /**
     * 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之外,我没有办法避免它。或者谁有更好的解决方案,请让我知道。

票数 4
EN

Stack Overflow用户

发布于 2020-06-14 08:22:54

如果有人仍然遇到这个问题:我通过将leakcanary更新到最新版本(在这一点上是2.4)来修复这个问题。看起来这是一次假阳性检测。我使用的是leakcanary 2.0 2.0beta 3。

票数 2
EN

Stack Overflow用户

发布于 2020-06-20 11:01:32

基于@EmMper的回答。如果你不需要onCancelListener,这里有一个解决办法。

代码语言:javascript
复制
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://stackoverflow.com/questions/53185154/leakcanary-dialogfragment-leak-detection
        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。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53185154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档