在android10以后,為了確保網(wǎng)絡(luò)數(shù)據(jù)的安全,對(duì)WebView在多進(jìn)程中的使用做了限制,每個(gè)進(jìn)程只能訪(fǎng)問(wèn)自己的網(wǎng)絡(luò)數(shù)據(jù),如Cookie,緩存,數(shù)據(jù)庫(kù)等等。所以需要為每個(gè)進(jìn)程制定數(shù)據(jù)存儲(chǔ)目錄。
錯(cuò)誤信息
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 以及之后版本不支持同時(shí)從多個(gè)進(jìn)程使用具有相同數(shù)據(jù)目錄的WebView
//為其它進(jìn)程webView設(shè)置目錄
private void fixWebViewMultiProcessCrashBug(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//為每個(gè)進(jìn)程設(shè)置數(shù)據(jù)目錄
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;
}