Android上多進程中使用webview的問題

在Andrid P以上的系統中,如果使用了多個進程,而且在這些進程中使用到了webview,那麼你可能遇到下面的異常提示

java.lang.RuntimeException: Using WebView from more than one process at once with the same data directory is not supported. https://crbug.com/558377

java.lang.RuntimeException: Using WebView from more than one process at once with the same data directory is not supported. https://crbug.com/558377
        at org.chromium.android_webview.AwBrowserProcess.b(PG:12)
        at n6.m(PG:33)
        at m6.run(PG:2)
        at org.chromium.base.task.TaskRunnerImpl.g(PG:11)
        at Nt.run(Unknown Source:2)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:6878)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)

這個錯誤有可能導致app崩潰退出。

原因就是Android P以及之後版本不支持同時從多個進程使用具有相同數據目錄的WebView

谷歌官方也是給瞭解決方法,就是給不同的進程中的webview設置不同的數據目錄

在Applicationd類的onCreate或者onBaseContextAttached方法中加入

public void onBaseContextAttached(Context base) {
    super.onBaseContextAttached(base);
    initWebViewDataDirectory(this);
}

/**
* 得到進程名稱
* @param context
* @return
*/
public static String getProcessName(Context context) {
    try {
            if (context == null) 
                return null;
            ActivityManager manager = (ActivityManager)
            context.getSystemService(Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningAppProcessInfo processInfo : 
                manager.getRunningAppProcesses()) {
                if (processInfo.pid == android.os.Process.myPid()) {
                    return processInfo.processName;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    return null;
}

/**
* 爲webView設置目錄後綴
* @param context
*/
@RequiresApi(api = Build.VERSION_CODES.P)
public static void initWebViewDataDirectory(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        String processName = getProcessName(context);
        if (!context.getPackageName().equals(processName)) {//判斷是否是默認進程名稱
            WebView.setDataDirectorySuffix(processName);
        }
    }
}

寫在最後,如果非必要,不要在多進程中使用webview,也儘量少修改webview的datadirectory,只在主進程初始化瀏覽器,否則高版本中多進程初始化webview會crash

發佈了8 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章