【问题标题】:Android WebView load from internal storage | Android 11 | Android RAndroid WebView 从内部存储加载 |安卓 11 |安卓
【发布时间】:2020-09-10 13:08:51
【问题描述】:

实际上我的要求是我想将动态文件加载到像图像一样的网页中。视频,音频等,它来自资产或应用程序自己的文件目录,这不是问题。

我尝试了以下两种方式。

方式 1

这是我的 html 文件在 assets 文件夹中,我在 assets 文件夹和内部文件夹中都有 123.jpg,

主页.html,

<!DOCTYPE html>
<html>
   <head>
      <title>Page Title</title>
   </head>
   <body>
      <h1>Image testing</h1>
      <p>Relative Path</p>
      <img src="123.jpg" alt="Italian Trulli" width="100%">
      <p>From Files Directory</p>
      <img src="file:////data/user/0/com.guna.testapplication/files/123.jpg" alt="Italian Trulli" width="100%">
   </body>
</html>

我正在将它加载到 webview 中

webView.loadUrl("file:///android_asset/Home.html")

这是我 29 的输出,

看,Asset 和 files 目录都按预期加载。

这里有 30 个,

这里仅从资产目录加载。并且文件目录没有加载。

方式 2

这里我从内部存储加载 html 和图像。

主页.html

<!DOCTYPE html>
<html>
   <head>
      <title>Page Title</title>
   </head>
   <body>
      <h1>Image testing</h1>
      <img src="123.jpg" alt="Italian Trulli" width="100%">
   </body>
</html>

我正在像这样加载 webview,

webView.loadUrl("file:////data/user/0/com.guna.testapplication/files/Home.html")

如果我的compileSdkVersion 29 和targetSdkVersion 29 效果很好,

29 的输出

如果我更改像 compileSdkVersion 30 和 targetSdkVersion 30 这样的 SdkVersion,这会给我访问被拒绝错误,

30 日输出

清单

<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:usesCleartextTraffic="true">
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

【问题讨论】:

标签: android


【解决方案1】:

找到答案,

当我们以Build.VERSION_CODES.R 为目标时,我们必须从setAllowFileAccess 将其显式设置为true,否则将不允许您加载file:// URLs。

所以解决办法是

webView.settings.allowFileAccess = true

在 Java 中,

webView.getSettings().setAllowFileAccess(true);

这两种情况都按预期工作。

【讨论】:

  • 确实如此。谢谢分享知识。在 Java 中:webView1.getSettings().setAllowFileAccess(true);
  • 天啊,我花了一整天的时间与 Android 11 解决这个问题。文档太没用了,为什么?它只是让我心烦。
  • 这里也一样....非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-07-07
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多