美文网首页Android BUGs
【bug】Android10 WebView在多进程中的使用

【bug】Android10 WebView在多进程中的使用

作者: aitality | 来源:发表于2022-10-24 11:13 被阅读0次

    在android10以后,为了确保网络数据的安全,对WebView在多进程中的使用做了限制,每个进程只能访问自己的网络数据,如Cookie,缓存,数据库等等。所以需要为每个进程制定数据存储目录。

    错误信息

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

    解决办法

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //必须放在这里
        fixWebViewMultiProcessCrashBug(base);
    }
    
    //Android P 以及之后版本不支持同时从多个进程使用具有相同数据目录的WebView
    //为其它进程webView设置目录
    private void fixWebViewMultiProcessCrashBug(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            //为每个进程设置数据目录
            String processName = getProcessName(context);
            WebView.setDataDirectorySuffix(processName);
        }
    }
    
    private 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;
    }
    

    相关文章

      网友评论

        本文标题:【bug】Android10 WebView在多进程中的使用

        本文链接:https://www.haomeiwen.com/subject/esxgzrtx.html