簡體   English   中英

Android WebView 從內部存儲加載 | 安卓 11 | 安卓 R

[英]Android WebView load from internal storage | Android 11 | Android R

實際上我的要求是我想像圖像一樣將動態文件加載到網頁中。 視頻、音頻等,它來自資產或應用程序自己的文件目錄,這不是問題。

我嘗試使用以下兩種方式。

方式一

這是我的 html 文件在資產文件夾中,我在資產文件夾和內部文件夾中都有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,

在此處輸入圖片說明

這里僅從資產目錄加載。 和文件目錄未加載。

方式二

在這里,我從內部存儲加載 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 29targetSdkVersion 29運行良好,

輸出 29

在此處輸入圖片說明

如果我更改 SdkVersion 像compileSdkVersion 30targetSdkVersion 30這會給我拒絕訪問錯誤,

輸出 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>

找到答案,

setAllowFileAccess 中,當我們針對Build.VERSION_CODES.R 時,我們必須將其顯式設置為true ,否則它將不允許您加載file:// URLs

所以解決辦法是

webView.settings.allowFileAccess = true

在爪哇,

webView.getSettings().setAllowFileAccess(true);

這在兩種情況下都按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM