美文网首页
Android(46)WebView 内存泄漏处理

Android(46)WebView 内存泄漏处理

作者: perry_Fan | 来源:发表于2022-08-09 17:09 被阅读0次

1. 初始化善用正确的 Context

// 让 WebView 使用 ApplicationContext
val webview = WebView(this.applicationContext)

不要在 xml 中去创建 WebView 标签

2. 释放相关内容

override fun onDestroy() {
    // webview?.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
    // webview?.clearView()
    webview?.loadUrl("about:blank")
    webview?.parent?.let {
        (it as ViewGroup).removeView(webview)
    }
    webview?.stopLoading()
    webview?.settings?.javaScriptEnabled = false
    webview?.clearHistory()
    webview?.clearCache(true)
    webview?.removeAllViewsInLayout()
    webview?.removeAllViews()
    webview?.webViewClient = null
    webview?.webChromeClient = null
    webview?.destroy()
    webview = null
    super.onDestroy()
}

相关文章

网友评论

      本文标题:Android(46)WebView 内存泄漏处理

      本文链接:https://www.haomeiwen.com/subject/mrabwrtx.html