Android concerning the use of multiple processes in webview

In the above Andrid P in the system, if multiple processes, and the use to webview in these processes, you may encounter the following exception Tips

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)

This error could lead to exit the app to crash.

The reason is that Android P and later versions do not support simultaneous use WebView directory with the same data from multiple processes

Google is also the official solution is to give a different process to set different data directory webview

Or adding onCreate method Applicationd class 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);
        }
    }
}

 

Released eight original articles · won praise 1 · views 50000 +

Guess you like

Origin blog.csdn.net/liudave/article/details/103957340