【问题标题】:Loading images from res or assets when web page in webview loads from server当 webview 中的网页从服务器加载时从 res 或 assets 加载图像
【发布时间】:2010-08-07 02:04:48
【问题描述】:

我想将网页从服务器发送到 Android 手机上的 WebView 组件。 我已经学习了如何让网页与 JavaScript 处理程序对话,以便本机应用程序可以与网页交互。 但是,我卡在图像上。

我希望来自服务器的网页以某种方式告诉应用要加载哪个图像(存储在 res 或 assets 中)。这样我也不必通过网络发送图像。这是可行的吗?就我的目的而言,这将使加载 WebView 页面的过程变得更快。

谢谢!

【问题讨论】:

    标签: android image webview


    【解决方案1】:

    您可以从远程 url 获取 http 响应,对其进行解析并通过字符串替换将远程图像 url 替换为本地图像 url。然后使用这个 html 代码在 webview 中显示。

    我想向下发送一个网页从服务器到 WebView

    您是在谈论“推动”而不是“拉动”机制(就像往常一样 loadUrl())?这仅在 2.2 中可用

    (问题:我想在您的情况下完全使用设备上的本地网页不起作用,因为您需要来自服务器的更新版本,对吗?您只知道图像不会改变,对吗?)

    用于获取远程 html 页面的示例代码 - 之后您将为您的图像 URL 进行字符串替换:

    /**
     * Downloads a remote file and stores it locally
     * @param from Remote URL of the file to download
     * @param to Local path where to store the file
     * @throws Exception Read/write exception
     */
    static private void downloadFile(String from, String to) throws Exception {
        HttpURLConnection conn = (HttpURLConnection)new URL(from).openConnection();
        conn.setConnectTimeout(15000); // timeout 15 secs
        conn.setDoInput(true);
        conn.connect();
        InputStream input = conn.getInputStream();
        FileOutputStream fOut = new FileOutputStream(to);
        int byteCount = 0;
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = input.read(buffer)) != -1) {
            fOut.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        fOut.flush();
        fOut.close();
    }
    

    你也可以使用

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://www.myurl.com");
    HttpResponse res = httpClient.execute(get);
    if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        InputStream input = res.getEntity().getContent();
        byte data[] = new byte[14];
        input.read(data);
        ....
    

    【讨论】:

    • 感谢您的回复。抱歉,我的问题没有应有的清楚。这确实有帮助,但让我问:如何通过 url 引用 res 或 assets 中的图像?似乎这有答案:stackoverflow.com/questions/1747072/…
    • 仅供参考,我不想“下拉”。我想简单地按需 loadUrl,从服务器返回的 html 直接引用存储在 .apk 中的图像文件。
    • 是的,您已经找到了如何访问资产的链接,这是正确的。
    猜你喜欢
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多