【问题标题】:WebView load images asynchronously from DatabaseWebView 从数据库异步加载图像
【发布时间】:2013-11-22 15:40:59
【问题描述】:

我想从本地数据库异步加载 HTML 中引用的图像。

现在我能做的就是用data:image/jpg;base64, img_base64_string> 替换<img src="abc.jpg">abc.jpg 部分,但这必须在呈现HTML get 之前完成。我想尽快显示 HTML 页面,然后加载图像。

  • 如何触发加载事件从数据库中加载图片?
  • 如何在不将其转换为 base64 的情况下正确设置 HTML 中加载的图像?

【问题讨论】:

  • 使用自定义 ContentProvider 并覆盖其 openFile 方法
  • 自定义的 ContentProvider 在这里并没有真正的帮助,因为你最后仍然需要一个文件路径——我没有,因为图像存储在数据库中。
  • 不,你不需要有文件路径,你为什么这么认为?
  • 我真的很想看到一些 ContentProvider.openFile() 代码从 byte[] 返回 ParcelFileDescriptor → 我是 ContentProvider 的新手。
  • 或者您可以创建一个临时文件并从该文件创建一个 ParcelFileDescriptor

标签: android database webview


【解决方案1】:

诀窍是创建一个 ParcelFileDescriptor.createPipe() 以通过流将数据库文件复制到 WebView。

LocalImageContentProvider.java

public class LocalImageContentProvider extends ContentProvider {

    private static final String AUTHORITY = "com.example.local.provider";
    public static final Uri CONTENT_URI = Uri.parse("content://"+ AUTHORITY +"/image");

    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) {
        String filename = uri.getLastPathSegment();

        // http://developer.android.com/reference/android/os/ParcelFileDescriptor.html#createPipe%28%29     
        // [0] is the reader, [1] is the writer
        ParcelFileDescriptor[] pipe = null;

        try {
            pipe = ParcelFileDescriptor.createPipe();

            // copy DB file through pipe to WebView
            new Thread(new PipeRunnable(
                    getInputStreamFromDbFile(filename),
                    new AutoCloseOutputStream(pipe[1])) )
            .start();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return (pipe[0]);
    }
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" >

    <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="19"/>

    <application>

        <!-- 'activity -->

        <provider android:exported="false"
            android:name=".provider.LocalImageContentProvider"
            android:authorities="com.example.local.provider"
        />

    </application>

</manifest>

要在 WebView 中加载图像,请使用 ContentProvider URI + "/image.jpg":
&lt;img src="content://com.example.local.provider/image/29.jpg"&gt;&lt;/img&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多