Android Jamendo源碼 圖片緩存實現 :
- package com.teleca.jamendo.util;
-
- import java.util.WeakHashMap;
-
- import android.graphics.Bitmap;
-
- /**
- * Caches downloaded images, saves bandwidth and user's
- * packets
- *
- * @author Lukasz Wisniewski
- */
- public class ImageCache extends WeakHashMap<String, Bitmap> {
-
- //WeakHashMap....add by gjican...
- private static final long serialVersionUID = 1L;
-
- public boolean isCached(String url){
- return containsKey(url) && get(url) != null;
- }
-
- }
在JamendoApplicatin中定義一個全局的getImageCache()來獲得當前應用程序圖片緩存 JamendoApplication.getInstance().getImageCache().put(mTaskUrl, bmp);
然後在每次下載圖片之前先進行判斷,看是否緩存裡存在此圖片,若有則直接顯示,否則調用DownloadTast()去下載
- public String doInBackground(String... params) {
-
- mTaskUrl = params[0];
- InputStream stream = null;
- URL imageUrl;
- Bitmap bmp = null;
-
- try {
- imageUrl = new URL(mTaskUrl);
- try {
- stream = imageUrl.openStream();
- bmp = BitmapFactory.decodeStream(stream);
- try {
- if(bmp != null){
- JamendoApplication.getInstance().getImageCache().put(mTaskUrl, bmp);
- Log.d(JamendoApplication.TAG, "Image cached "+mTaskUrl);
- } else {
- Log.w(JamendoApplication.TAG, "Failed to cache "+mTaskUrl);
- }
- } catch (NullPointerException e) {
- Log.w(JamendoApplication.TAG, "Failed to cache "+mTaskUrl);
- }
- } catch (IOException e) {
- Log.w(JamendoApplication.TAG, "Couldn't load bitmap from url: " + mTaskUrl);
- } finally {
- try {
- if(stream != null){
- stream.close();
- }
- } catch (IOException e) {}
- }
-
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- return mTaskUrl;
- }