Welcome to follow the official wechat account: FSA Full stack action 👋
Resolve WebView memory leaks
The key points to resolve WebView memory leaks are as follows:
- Instead of using XML, use code to new the WebView
- Don’t let webViews hold Context references to Activities/fragments (core)
- When destroyed, stops loading the WebView and removes it from the parent control
Initialize the WebView
The main reason for WebView memory leakage is that the Context of the Activity/Fragment is referenced, and the WebView itself has design problems, so the Activity/Fragment cannot be released immediately. Since the WebView can’t immediately release the Context, let it reference the global Context:
// Let WebView use ApplicationContext
val webview = WebView(this.applicationContext)
Copy the code
Remember: Do not create webViews in XML using the
tag
2. Destroy the WebView
To ensure that the WebView does not continue meaningless loading in the background when the Activity/Fragment interface is destroyed, and to avoid accidental leakage caused by reference to the WebView by the parent control, the following two steps are required:
- Removes the WebView from its parent control
- Let the WebView stop loading the page and release it
override fun onDestroy(a) {
// webview? .loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
// webview? .clearView()webview? .loadUrl("about:blank") webview? .parent? .let { (itasViewGroup).removeView(webview) } webview? .stopLoading() webview? .settings? .javaScriptEnabled =falsewebview? .clearHistory() webview? .clearCache(true) webview? .removeAllViewsInLayout() webview? .removeAllViews() webview? .webViewClient =nullwebview? .webChromeClient =nullwebview? .destroy() webview =null
super.onDestroy()
}
Copy the code