记一次 WebView 异常崩溃问题(Render Process)

问题描述:

因公司业务需要,现在 Android 存在的方式基本都是原生与 h5 页面共存的情况。近日发现,当应用中存在多个 WebView 实例去渲染 h5 页面的时候,就有可能会出现程序异常崩溃的情况,在低端机中表现较为明显。

出现的原因:

通过日志排查发现,在 log 控制台除了打印一堆 dump 日志之外,还有一行格外鲜艳的话:

Render process (11786)'s crash wasn't handled by all associated webviews, triggering application crash.

这句话大致的意思就是,由于相关联的所有 WebView 没有处理渲染进程的 crash,进而触发了我们 application 的 crash。
查阅官方文档,发现 WebViewClient 中有一个回调方法 onRenderProcessGone

    /**
     * Notify host application that the given WebView's render process has exited.
     *
     * Multiple WebView instances may be associated with a single render process;
     * onRenderProcessGone will be called for each WebView that was affected.
     * The application's implementation of this callback should only attempt to
     * clean up the specific WebView given as a parameter, and should not assume
     * that other WebView instances are affected.
     *
     * The given WebView can't be used, and should be removed from the view hierarchy,
     * all references to it should be cleaned up, e.g any references in the Activity
     * or other classes saved using {@link android.view.View#findViewById} and similar calls, etc.
     *
     * To cause an render process crash for test purpose, the application can
     * call {@code loadUrl("chrome://crash")} on the WebView. Note that multiple WebView
     * instances may be affected if they share a render process, not just the
     * specific WebView which loaded chrome://crash.
     *
     * @param view The WebView which needs to be cleaned up.
     * @param detail the reason why it exited.
     * @return {@code true} if the host application handled the situation that process has
     *         exited, otherwise, application will crash if render process crashed,
     *         or be killed if render process was killed by the system.
     */
    public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
        return false;
    }

从官方的注释中可以看到,当WebView 的 Render Process 被移除的时候就会回调该方法,再继续跟到里面看具体的实现,我这用的调试机是荣耀的,所以这里的实现是一个SaveWebView 的类。

        @SuppressLint({"NewApi"})
        public boolean onRenderProcessGone(WebView var1, RenderProcessGoneDetail var2) {
            return this.O != null ? this.O.onRenderProcessGone(var1, var2) : super.onRenderProcessGone(var1, var2);
        }

一目了然,这里的 O 就是 WebViewClient,当 WebViewClient 不为空的时候就会调用进来。
再回到上一步,发现 onRenderProcessGone 是虚类 WebViewRenderProcess 里面的一个方法。


/**
 * WebViewRenderProcess provides an opaque handle to a {@link WebView} renderer.
 */
public abstract class WebViewRenderProcess {
    /**
     * Cause this renderer to terminate.
     *
     * <p>Calling this on a not yet started, or an already terminated renderer will have no effect.
     *
     * <p>Terminating a renderer process may have an effect on multiple {@link WebView} instances.
     *
     * <p>Renderer termination must be handled by properly overriding
     * {@link WebViewClient#onRenderProcessGone} for every WebView that shares this
     * renderer. If termination is not handled by all associated WebViews, then the application
     * process will also be terminated.
     *
     * @return {@code true} if it was possible to terminate this renderer, {@code false} otherwise.
     */
    public abstract boolean terminate();

    public WebViewRenderProcess() {
    }
}

再看看这个类在哪有引用到,接着继续往下跟发现在 WebViewRenderProcessClient 里面有个 onRenderProcessUnresponsive 方法。
关于 WebViewRenderProcessClient 有这么一段注释:

/**
 * Used to receive callbacks on {@link WebView} renderer events.
 *
 * WebViewRenderProcessClient instances may be set or retrieved via {@link
 * WebView#setWebViewRenderProcessClient(WebViewRenderProcessClient)} and {@link
 * WebView#getWebViewRenderProcessClient()}.
 *
 * Instances may be attached to multiple WebViews, and thus a single renderer event may cause
 * a callback to be called multiple times with different WebView parameters.
 */

大致意思就是说,这个类会接收 render 进程的事件回调,然后做一些判断处理,回调相应抑或是不响应。

    /**
     * Called when the renderer currently associated with {@code view} becomes unresponsive as a
     * result of a long running blocking task such as the execution of JavaScript.
     *
     * <p>If a WebView fails to process an input event, or successfully navigate to a new URL within
     * a reasonable time frame, the renderer is considered to be unresponsive, and this callback
     * will be called.
     *
     * <p>This callback will continue to be called at regular intervals as long as the renderer
     * remains unresponsive. If the renderer becomes responsive again, {@link
     * WebViewRenderProcessClient#onRenderProcessResponsive} will be called once, and this method
     * will not subsequently be called unless another period of unresponsiveness is detected.
     *
     * <p>The minimum interval between successive calls to {@code onRenderProcessUnresponsive} is 5
     * seconds.
     *
     * <p>No action is taken by WebView as a result of this method call. Applications may
     * choose to terminate the associated renderer via the object that is passed to this callback,
     * if in multiprocess mode, however this must be accompanied by correctly handling
     * {@link WebViewClient#onRenderProcessGone} for this WebView, and all other WebViews associated
     * with the same renderer. Failure to do so will result in application termination.
     *
     * @param view The {@link WebView} for which unresponsiveness was detected.
     * @param renderer The {@link WebViewRenderProcess} that has become unresponsive,
     * or {@code null} if WebView is running in single process mode.
     */
    public abstract void onRenderProcessUnresponsive(
            @NonNull WebView view, @Nullable WebViewRenderProcess renderer);

从注释中我们可以看到,当 Render 进程长时间无响应的时候,就会触发这个方法。比如因为 JavaScript 长时间无响应、输入相应事件长时间无响应抑或是导航至新的 url 无响应等。
到这里,基本就比较明晰了。也就是说,当 WebView 的任务过重,如 JavaScrip 长时间无响应,抑或是其他导致响应事件过长的情况,都有可能会触发 render 进程移除,如果不加以处理,就会导致我们的应用进程被强制停止。

解决办法:

既然当系统 WebView 的 Render 进程被移除时会给到我们相应的回调,因此我们直接重写 onRenderProcessGone 方法。
simple代码大致如下,根据实际业务进行处理,仅供参考。

            @Override
            public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
                    return false;
                }
                // 仅对我们自己的 webview 做处理
                if ( view == mWebView) {
                  // 获取 webview 所在父布局
                    ViewGroup parent = (ViewGroup) mWebView.getParent();
                    ViewGroup.LayoutParams params = mWebView.getLayoutParams();
                    // 把无效不可用的 webview 从布局中移除
                    destroyWebView();
                   // 重新创建新的 webview
                    WebView newWebView = new WebView(getActivity());
                    newWebView.setId(R.id.webView);
                    parent.addView(newWebView, 0, params);
                    Bundle bundle = getArguments();
                    // 重走初始化流程,渲染 UI,加载 url
                    initView(root);
                    return true;
                }
                return super.onRenderProcessGone(view, detail);
            }

以上。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339

推荐阅读更多精彩内容