Gunaseelan
Gunaseelan

Reputation: 15525

Android WebView load from internal storage | Android 11 | Android R

Actually my requirement is I want to load dynamic files into WebPage like image. video, audio etc.., it's either from asset or apps own files directory, that's not a problem.

I tried using following two ways.

Way 1

Here is my html file is in assets folder, and I have 123.jpg in both assets folder and also internal folder,

Home.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>

And I am loading it into webview like

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

And here is my output for 29,

enter image description here

Look, both from Asset and files directory loaded as expected.

And here is for 30,

enter image description here

Here only from asset directory loaded. And files directory not loaded.

Way 2

Here I'm loading both html and image from internal storage.

Home.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>

And I'm loading webview like this,

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

If my compileSdkVersion 29 and also targetSdkVersion 29 this works well,

Output for 29

enter image description here

If I change SdkVersion like compileSdkVersion 30 and also targetSdkVersion 30 this gives me access denied error,

Output on 30

enter image description here

Manifest

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

Upvotes: 17

Views: 5753

Answers (1)

Gunaseelan
Gunaseelan

Reputation: 15525

Found the Answer,

From setAllowFileAccess we have to explicitly set it to true when we are targeting Build.VERSION_CODES.R, otherwise it wont allow you to load file:// URLs.

So the solution is

webView.settings.allowFileAccess = true

In Java,

webView.getSettings().setAllowFileAccess(true);

This works as expected for both scenario.

Upvotes: 33

Related Questions