Android11.0如何用webview加载本地图片?

How to load local images with webview on Android 11.0?

Android11.0如何使用WebView加载本地存储图片?

有富文本:

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

/storage/emulated/0/Pictures/IMG_20210604_110651.jpg为本地图片

这是加载图片的部分代码:

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

我的代码可以在 android 10 和 10 下工作,但在 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" />

已获得这些权限。

任何帮助在此先感谢。

问题的原因最终找到了。 这是因为webSetting.setAllowFileAccess方法在29及之前的版本默认为true,在30及之后的版本默认为false。

 /**
 * 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);

所以添加如下代码解决这个问题:

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

当然让 targetSdkVersion <=29 也可以。