无法在 API 级别 30 上加载本地 html 文件

Jch*_*han 7 android android-webview android-11

我的应用程序加载位于getFilesDir()via下的本地 html 文件WebView#loadUrl()
之前targetSdkVersion = 29,下面的代码正在运行。

        copyAssetsFile(this, "sample.html", getFilesDir().getAbsolutePath());
        webView.getSettings().setJavaScriptEnabled(true);
        String url = "file://" + getFilesDir().getAbsolutePath() + "/sample.html";
        webView.loadUrl(url);
    }

    private static void copyAssetsFile(Context context, String fileName, String directoryPath) {
        try {
            InputStream inputStream = context.getResources().getAssets().open(fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(
                    new File(directoryPath, fileName), false);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) >= 0) {
                fileOutputStream.write(buffer, 0, length);
            }

            fileOutputStream.close();
            inputStream.close();
Run Code Online (Sandbox Code Playgroud)

完整示例在这里

但是,它在更改后不起作用targetSdkVersion = 30

  • WebView 响应 net::ERR_ACCESS_DINIED
  • 如果它位于,可以加载本地 html android_asset

如何加载本地 html 文件targetSdkVersion = 30
是不是改成被Android FW拒绝了??

小智 12

WebSettings#setAllowFileAccess()R出于安全原因,当您的应用面向及以上时,默认为 false ,请注意,您需要将 API 级别设置为 30。 https://developer.android.com/reference/android/webkit/WebSettings#setAllowFileAccess(boolean)