Multi-process Webview combat

"Android P 以及之后版本不支持同时从多个进程使用具有相同数据目录的WebView"

The above is the official description. In vernacular terms, if there are multiple processes A, B, C in an app, and WebView is used in processes A, B, and C, in Android P and later An error will be reported when running in the version:

    //Android P 以及之后版本不支持同时从多个进程使用具有相同数据目录的WebView
        //为其它进程webView设置目录
     
        @RequiresApi(api = 28)
        public void webviewSetPath(Context context) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                String processName = getProcessName(context);
                if (!MainProcessName.equals(processName)) {//判断不等于默认进程名称
                    WebView.setDataDirectorySuffix(processName);
                }
            }
        }
     
        public String getProcessName(Context context) {
            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;
                }
            }
            return null;
        }

The call of webviewSetPath() must be called when the process is initialized, such as in Application, and this line of code needs to be called before other SDKs, etc. are initialized, otherwise other errors will be reported.

 

Guess you like

Origin blog.csdn.net/xifei66/article/details/108713556