Android碎片Webview内存泄漏

3

我需要帮助识别关于片段和Web视图的代码问题。我尝试实施其他线程中的一些解决方案,但都没有成功。我已经测试过同一片段在没有创建Web视图的情况下被替换,没有泄漏。有什么想法吗?如果没有,是否可以提出另一种解决方案?

这是我的Web视图片段:

public class CustomWebViewFragment extends PageFragment
{

private LinearLayout mWebContainer;
private WebView mWebView;


/**
 * public View onCreateView(LayoutInflater inflater, ViewGroup container,
 * Bundle savedInstanceState)
 */
@SuppressLint("SetJavaScriptEnabled")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragment_one, container, false);

    //If I comment this line out, there is no memory leak
    mWebView = new WebView(this.getActivity().getApplicationContext()); 

    return v;
}


/**
 * public void onDestroy()
 */
@Override
public void onDestroy()
{
    super.onDestroy();
    if (mWebView != null)
    {
        mWebView.loadUrl("about:blank");
        mWebView.destroy();
        mWebView = null;
    }
}

这里是我如何改变片段的方法:

@Override
public void onNavSelected(String page)
{
    if (page != null && !page.equals(""))
    {
        System.gc();
        if (page.equalsIgnoreCase(GlobalConstants.PAGE_1))
        {
            mCurrent = getFragment(); // Creates a new fragment
            getSupportFragmentManager().beginTransaction()
                .replace(R.id.main_fragment, mCurrent).commit();
        }
    }
}

感谢mWebView.loadUrl("about:blank")。这解决了我的内存泄漏问题! - undefined
1个回答

3
改变
//If I comment this line out, there is no memory leak
mWebView = new WebView(this.getActivity().getApplicationContext()); 

&

@Override
public void onDestroy()
{
    super.onDestroy();
    if (mWebView != null)
    {
        mWebView.loadUrl("about:blank");
        mWebView.destroy();
        mWebView = null;
    }
}

To

mWebView = new WebView(getActivity()); 

&

@Override
public void onDestroy()
{
    // null out before the super call
    if (mWebView != null)
    {
        mWebView.loadUrl("about:blank");
        mWebView = null;
    }
    super.onDestroy();
}

你能在你的问题中添加内存泄漏日志语句吗?这将有助于缩小范围。 - undefined
WebView只是在应用程序的其他地方引发了一个泄漏问题。这是正确的销毁WebView的方法。标记为答案。 - undefined
我觉得你的意思是onDestroyView(),而不是onDestroy()。否则可能会导致内存泄漏。根据Fragment的生命周期,有一种情况是onCreateView()可以被多次调用,但是onDestroy()只会被调用一次。 - undefined
我相当确定内存泄漏是由于使用应用上下文而不是活动上下文来创建Web视图所致。这可以通过使用XML布局(或在Java构造函数中使用活动上下文)轻松避免。 - undefined

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