本文共 1168 字,大约阅读时间需要 3 分钟。
欢迎关注微信公众号:
要解决 WebView 内存泄漏的要点如下:
WebView 内存泄露的主要原因是引用了 Activity/Fragment 的 Context,加之 WebView 本身的设计问题,导致 Activity/Fragment 无法被即时释放,既然 WebView 无法即时释放 Context,那就让它引用全局的 Context 就好了:
// 让 WebView 使用 ApplicationContextval webview = WebView(this.applicationContext)
切记:不要在 xml 中使用
<WebView>
标签创建 WebView
为了保证 Activity/Fragment 界面销毁时,WebView 不要在后台继续进行没有意义的加载,并且避免父控件对 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()}
转载地址:http://zphpf.baihongyu.com/