欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

WebView渲染異常導(dǎo)致閃退問題的解決方案

 更新時間:2025年02月27日 10:37:29   作者:封妖九禁蒼天泣  
這篇文章主要介紹了WebView渲染異常導(dǎo)致閃退問題的解決方案,文中通過設(shè)置WebViewClient重寫onRenderProcessGone()方法并移除、重新創(chuàng)建Web容器來解決該問題,需要的朋友可以參考下

背景:

App主頁面使用了大量WebView容器(10個以上)顯示圖表信息,最新發(fā)現(xiàn)bugly上面出現(xiàn)一些關(guān)于瀏覽器Native Crash,如下:

經(jīng)排查,是WebView渲染失敗導(dǎo)致Crash,可以通過webView.loadUrl("chrome://crash")模擬。

解決方法:

1、通過設(shè)置WebViewClient,重寫onRenderProcessGone()返回值,強(qiáng)制返回true,表示在WebView發(fā)生異常時,自己處理,這樣App就不會出現(xiàn)Crash。這么做App雖然沒有Crash,但是主頁面的WebView內(nèi)容卻看不到了,看到的是白色/黑色背景,體驗(yàn)極差。

2、要想解決WebView內(nèi)容不可見問題,還需要在Web出現(xiàn)異常的時候,移除原有Web容器,重新創(chuàng)建一個Web容器,代碼如下:

class ReportWebView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : wendu.dsbridge.BaseWebView(context, attrs) {

    var reloadFun: ((any: ReportWebView) -> Unit)? = null
    private var parentViewGroup: ViewGroup? = null

    init {
        webViewClient = CustomWebViewClient()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        parentViewGroup = parent as? ViewGroup
    }

    private inner class CustomWebViewClient : WebViewClient() {

        override fun onRenderProcessGone(view: WebView?, detail: RenderProcessGoneDetail?): Boolean {
            // 所有的web都crash,所以都需要重建
            recreateWebViewAndReload(view)
            return true
        }
    }

    private fun recreateWebViewAndReload(view: WebView?) {
        val originalUrl = view?.url// 原始webView地址
        val isVisible = view?.isVisible
        val lp = this.layoutParams
        // 移除舊的 WebView
        val index = indexInParent()
        if (parentViewGroup != null) {
            parentViewGroup?.removeView(this)
        }
        destroy()// 銷毀

        // 重新創(chuàng)建 WebView
        val newWebView = ReportWebView(context)
        reloadFun?.invoke(newWebView)
        newWebView.reloadFun = reloadFun
        newWebView.id = id
        newWebView.layoutParams = lp
        newWebView.isVisible = isVisible.nullOr(false)
        originalUrl?.let { newWebView.loadUrl(it) }

        // 將新的 WebView 添加回布局中
        parentViewGroup?.addView(newWebView, index)

        // 更新引用
        parentViewGroup = newWebView.parent as? ViewGroup
    }

    private fun indexInParent(): Int {
        return parentViewGroup?.indexOfChild(this) ?: -1
    }

}

本項(xiàng)目橋接使用的是DSBridge三方庫,在創(chuàng)建Web容器需要設(shè)置addJavascriptObject(),即reloadFun函數(shù)。

注意事項(xiàng):

1、同一個頁面只要有一個渲染異常,會導(dǎo)致所有Web容器異常,所以所有Web容器都要重新創(chuàng)建,不可以根據(jù)Web可見狀態(tài)只創(chuàng)建可見的Web。

2、在使用的時候,原有的Web容器已被移除,需要使用最新的Web容器,否則就會報錯。上述代碼中,新的Web容器id跟移除的一樣,所以也很容易拿到新的Web容器,代碼如下:

/**
 * 獲取真實(shí)的webView,之前的web可能被銷毀
 * @param id web id
 */
private fun getRealWebView(id: Int): ReportWebView {
    return mBinding.root.findViewById(id)
}

總結(jié) 

到此這篇關(guān)于WebView渲染異常導(dǎo)致閃退問題解決方案的文章就介紹到這了,更多相關(guān)WebView渲染異常閃退內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關(guān)文章

最新評論