使用Android的系统缓存

时间:2011-06-01 07:11:12

标签: android image caching download system

我希望在按照之前的说明下载图像时使用Android的系统缓存:android system cache。我能够得到以下代码,但日志语句告诉我永远不会从缓存中读取图像。

try {
    //url = new URL("http://some.url.com/retrieve_image.php?user=" + username);
    URL url = new URL("http://some.url.com/prof_pics/b4fe7bdfa174ff372c9f26ce6f78f19c.png");
    URLConnection connection = url.openConnection();
    connection.setUseCaches(true);
    Object response = connection.getContent();
    if (response instanceof Bitmap) {
        Log.i("CHAT", "this is a bitmap");
        current_image.setImageBitmap((Bitmap) response);
    }
    else {
        Log.i("CHAT", "this is not a bitmap");
        Log.i("CHAT", response.toString());
        InputStream is = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        current_image.setImageBitmap(BitmapFactory.decodeStream(bis));
    }
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

我尝试了两种不同类型的请求,一种是通过返回图像的PHP脚本和另一种直接访问图像文件的请求。我连续多次刷新相同的图像,似乎永远不会被缓存。对于直接图像访问,我得到:

05-31 23:45:12.177 I/CHAT    ( 2995): this is not a bitmap
05-31 23:45:12.177 I/CHAT    ( 2995): org.apache.harmony.luni.internal.net.www.protocol.http.FixedLengthInputStream@40c1c660`

对于间接图像访问,我始终得到:

05-31 23:45:14.550 I/CHAT    ( 2995): this is not a bitmap
05-31 23:45:14.550 I/CHAT    ( 2995): org.apache.harmony.luni.internal.net.www.protocol.http.ChunkedInputStream@40c02448

1 个答案:

答案 0 :(得分:4)

我发现了一种更好的方法。如果其他人在关注android system cache链接后遇到问题,请改用此Google developer's blog post。该博客文章中的源代码是为ListView设计的,但我将其用于所有图像检索。它在AsyncTask中下载图像,在下载时放置临时图像,具有图像缓存。最后一部分在博客文章中列为“未来项目”,但如果您下载源代码,则实现缓存。我不得不稍微修改代码,因为2.1中不支持AndroidHttpClient。我将其切换为URL连接。到目前为止,这看起来是一个伟大的图像下载类。我们只希望它不会影响我们已经陷入困境的内存管理问题。