当webview中的网页从服务器加载时,从res或资源加载图像

时间:2010-08-07 02:04:49

标签: android image webview

我想将一个网页从服务器发送到Android手机上的WebView组件。 我已经学会了如何使网页与JavaScript处理程序通信,因此本机应用程序可以与网页进行交互。 但是,我坚持使用图像。

我希望来自服务器的网页以某种方式告诉应用程序加载哪个图像(存储在res或资产中)。这样我也不必通过电线发送图像。这可行吗?它将使加载WebView页面的过程更加快速。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以从远程网址获取http响应,解析它并通过字符串替换替换远程图像网址和本地网址。然后使用此HTML代码在webview中显示。

  

我想从服务器发送网页到WebView

您是在谈论'推'还是'拉'机制(就像loadUrl()一样)?这只适用于2.2

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

获取远程html页面的示例代码 - 之后您将为图片网址替换字符串:

/**
 * 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);
    ....
相关问题