Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 5.1 系統 WebView 內存洩漏場景分析

編輯:關於 Android 程式設計

問題現象

(本文引自零號路的私人博客,本人在瀏覽框架的開發過程中,用該方式規避了內存洩露的問題。)

在 Android 5.1 系統中,會發現 App 存在 WebView 洩漏情況,而且還比較嚴重,並且只發生在 Android 5.1 系統。

GC roots 如下:

每新打開一次這個 WebViewActivity,就會發生一次該 WebView 實例無法釋放的情況,新增一個物件。上圖中的兩個 AppSearchWebView 實例,就是由於打開了兩次導致。

問題分析

出現這個問題分析起來還是比較簡單的。根據這個引用關係,可以直觀看到是由於 AppSearch(extends Application)的 mComponentCallbacks 一直在強引用 AwComponentCallbacks,導致無法釋放,然後 AwComponentCallbacks → AwContents → AppSearchWebView。

透過分析代碼,發現關鍵在於 AwContents 這裡的 AwComponentCallbacks 為什麼沒有釋放:

 @Override public void onAttachedToWindow() { if (isDestroyed()) return; if (mIsAttachedToWindow) { Log.w(TAG, "onAttachedToWindow called when already attached. Ignoring"); return; } ...... mComponentCallbacks = new AwComponentCallbacks(); mContext.registerComponentCallbacks(mComponentCallbacks); } @Override public void onDetachedFromWindow() { if (isDestroyed()) return; if (!mIsAttachedToWindow) { Log.w(TAG, "onDetachedFromWindow called when already detached. Ignoring"); return; } ...... if (mComponentCallbacks != null) { mContext.unregisterComponentCallbacks(mComponentCallbacks); mComponentCallbacks = null; } ...... } 

看這段代碼看不出什麼問題:onAttach 時 register,detach 時 unregister,按理不會有問題。那到底是為什麼呢?難道是由於 if (isDestroyed()) return 這條 return 引起的?當呼叫 WebView.destroy() 後,這個判斷會回傳 true。

我們看看哪裡調用了 webview.destroy():

// source from WebViewActivity @Override protected void onDestroy() { super.onDestroy(); if (mWebView != null) { mWebView.destroy(); } } 

很多應用應該都是這麼做的,包括系統瀏覽器,在 Activity destroy 的時候呼叫 webview 的 destroy,並且一直工作得很好。透過調試發現,確實是由於此調用導致的:onDestroy 發生在 onDetach 之前。

那為什麼 Android 5.1 之前的代碼沒有問題呢?看下代碼:

 // AwContents.java @Override public void onDetachedFromWindow() { if (!mIsAttachedToWindow) { Log.w(TAG, "onDetachedFromWindow called when already detached. Ignoring"); return; } ...... if (mComponentCallbacks != null) { mContext.unregisterComponentCallbacks(mComponentCallbacks); mComponentCallbacks = null; } ...... } 

相對於 5.1 的代碼,這裡少了那句 if (isDestroyed()) return;。正是這句判斷,使得 5.1 上在 destroy 之後 onDetachedFromWindow 提前返回,跳過了 unregisterComponentCallbacks,導致洩漏。

規避方法

解決方案:在 destroy 之前,把 WebView 從 parent 中 remove 掉,同樣可以提前 detach:

 protected void onDestroy() { if (mWebView != null) { ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } super.onDestroy(); }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved