1. 程式人生 > >webview 記憶體洩露解決辦法

webview 記憶體洩露解決辦法

最近開始使用leakCanary為app進行記憶體洩露的檢測

遇到了webview.mContext導致activity記憶體洩露

(不過在android 6.0的機子上沒有遇到這樣的問題)

經過搜尋,在http://bugly.qq.com/bbs/forum.php?mod=viewthread&tid=516 裡找到了原因

面對這樣的問題,我們暫時可以通過在layout中放置webview的地方用framelayout代替

    <FrameLayout
        android:id="@+id/webview_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>


再動態將新建的webview加進framelayout中

frameLayout = (FrameLayout) findViewById(R.id.webview_container);
        webView = new WebView(getApplicationContext());
        frameLayout.addView(webView);

在activity onDestroy的時候將webview與activity解除關聯,我們可以從文件看出原因

webview 的destroy文件

    /**
     * Destroys the internal state of this WebView. This method should be called
     * after this WebView has been removed from the view system. No other
     * methods may be called on this WebView after destroy.
     */
    public void destroy() {
        checkThread();
        mProvider.destroy();
    }
mProvider(WebviewProvider)的destroy文件
    /**
     * See {@link WebView#destroy()}.
     * As well as releasing the internal state and resources held by the implementation,
     * the provider should null all references it holds on the WebView proxy class, and ensure
     * no further method calls are made to it.
     */
    public void destroy();