2011-06-01 50 views
2

我想按照以下指令下载图像时使用Android系统高速缓存:android system cache。我能够得到以下代码,但日志语句告诉我图像永远不会从缓存中读取。使用Android系统高速缓存

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.har[email protected]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[email protected]40c02448 

回答

4

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

+0

伟大的帮助,感谢指出这个职位! – 2011-07-19 13:08:24