How to load local images with webview on Android 11.0?

Viewed 1063

How to use the WebView to load the local storage pictures on Android 11.0?

There is a richtext :

<img src="/storage/emulated/0/Pictures/IMG_20210604_110651.jpg" alt="dachshund" width="100%"><br><br>

/storage/emulated/0/Pictures/IMG_20210604_110651.jpg is a local image.

This is part code of how to load the image:

String data = "<img src=\"/storage/emulated/0/Pictures/IMG_20210604_110651.jpg\" alt=\"dachshund\" width=\"100%\"><br><br>";
binding.webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

My code could work Under android 10 and 10,but not work in Android 11.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

These permissions have been obtained.

Any help Thanks in advance.

1 Answers

The cause of the problem was eventually discovered. This is because the webSetting.setAllowFileAccess method defaults to true in 29 and earlier versions, and false in 30 and later versions.

 /**
 * Enables or disables file access within WebView.
 * Note that this enables or disables file system access only. Assets and resources
 * are still accessible using file:///android_asset and file:///android_res.
 * <p class="note">
 * <b>Note:</b> Apps should not open {@code file://} URLs from any external source in
 * WebView, don't enable this if your app accepts arbitrary URLs from external sources.
 * It's recommended to always use
 * <a href="{@docRoot}reference/androidx/webkit/WebViewAssetLoader">
 * androidx.webkit.WebViewAssetLoader</a> to access files including assets and resources over
 * {@code http(s)://} schemes, instead of {@code file://} URLs. To prevent possible security
 * issues targeting {@link android.os.Build.VERSION_CODES#Q} and earlier, you should explicitly
 * set this value to {@code false}.
 * <p>
 * The default value is {@code true} for apps targeting
 * {@link android.os.Build.VERSION_CODES#Q} and below, and {@code false} when targeting
 * {@link android.os.Build.VERSION_CODES#R} and above.
 */
public abstract void setAllowFileAccess(boolean allow);

So add follow code solve this problem:

binding.webView.getSettings().setAllowFileAccess(true);

of cause let targetSdkVersion <=29 will also okey.

Related