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

标签 android android-webview android-11

我的应用程序加载位于 getFilesDir() 下的本地 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();
完整示例为 here .
但是,更改后它不起作用targetSdkVersion = 30 .
  • WebView 回复 net::ERR_ACCESS_DINIED
  • 如果它位于 android_asset,则可以加载本地 html

  • 如何在 targetSdkVersion = 30 上加载本地 html 文件?
    是否更改为被Android FW拒绝?

    最佳答案

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

    关于android - 无法在 API 级别 30 上加载本地 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63128749/

    相关文章:

    android - 如何绘制一条从拖放操作的源到目标的线?

    android-layout - 我的 WebView 没有填充选项卡的屏幕(但没有 pb 填充手机的屏幕)

    android - startActivity 在 Android 11 中抛出异常

    android - **编辑** 如何在我的 android 应用程序中设置缓存清除按钮

    android - 一次性权限导致后台计划作业和警报被取消

    Android 11 - native C++ 库的 System.loadLibrary 需要 60 多秒,在 Android 10 及更低版本上运行速度非常快

    android - 从基于 Titan Appcelerator 构建的 Android 应用程序调用电话

    android - 使用 Android Designer Xamarin 打开 *.axml 文件时 VS 2015 崩溃

    java - Android 应用程序在模拟器和设备上不断崩溃

    javascript - 使用来自已加载网页的 JavaScript 调用重新加载 WebView