如何使用缓存来进行图像下载?

时间:2010-11-26 16:59:13

标签: android

我正在使用图像下载逻辑从网上显示图像,我想只在第一次下载图像,下次不要从网上下载图像,因为第一次下载图像存储在缓存中,所以我显示来自catch内存的图像,如果不在高速缓冲存储器中退出该图像,否则下载不需要从网上下载该图像,怎么可能?

谢谢朋友们。

5 个答案:

答案 0 :(得分:1)

如果你不想在这里重新发明轮子,可以使用内置缓存的droid-fu图像加载,或者深入了解cachefu类以获取更多信息。特别是,AbstractCache是两级缓存的良好基础;在这种情况下,它保留了较小的内存缓存,如果SD卡可用,它将保留额外的内容。

答案 1 :(得分:0)

我不是Android开发者,但我相信应该有办法写入本地内存。我写到一个目录。我猜这个图像是从一个字节数组回来的,你可以保存到本地mem。然后你可以随时再次阅读它。

答案 2 :(得分:0)

您可以使用Hashtable缓存实现“CacheManager”单例类,因此当您下载完成时,将缓存对象添加到cache.put(imageUrl,imageView)。必须在单例中执行此操作以在应用程序生命周期中保留缓存。

答案 3 :(得分:0)

这是图像缓存类的链接。

http://theandroidcoder.com/utilities/android-image-download-and-caching/

它似乎运行良好,并支持内存和SD卡缓存

答案 4 :(得分:0)

在imageLoader类下面,以便在下载图像后保持缓存内存和磁盘内存到磁盘中的映像存储。

public class MyImageLoader {

private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
private static final String DISK_CACHE_SUBDIR = "ImageCache";
private DiskLruImageCache mDiskLruImageCache;
private ExecutorService executorService;
private LruCache<String, Bitmap> mMemoryCache;
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
private int byteCounts;
private int requiredHeight = 100, requiredWidth = 100; // setting default height & width as 100
private final int default_icon = R.drawable.no_image_friend;
CommonMethod mCommonMethod;

public MyImageLoader(Context context) {

    executorService = Executors.newFixedThreadPool(2);
    final int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = 1024 * 1024 * memClass / 8;

    mCommonMethod = new CommonMethod(context);
    mDiskLruImageCache = new DiskLruImageCache(context, DISK_CACHE_SUBDIR, DISK_CACHE_SIZE, CompressFormat.PNG, 70);

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {

        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            byteCounts = bitmap.getRowBytes() * bitmap.getHeight();
            return byteCounts;
        }
    };
}

public void ExecuteLoading(String urlString, ImageView mImageView) {

    imageViews.put(mImageView, urlString);
    Bitmap bitmap = getBitmapFromMemCache(urlString);

    if (bitmap != null){
        mImageView.setImageBitmap(bitmap);
    }
    else {
        executorService.submit(new LoadImages(urlString, mImageView));
        mImageView.setImageResource(default_icon);
    }
}

boolean ImageViewReused(String urlString, ImageView mImageView){
    String tag=imageViews.get(mImageView);
    if(tag==null || !tag.equals(urlString))
        return true;
    return false;
}

class LoadImages implements Runnable {
    String urlString;
    ImageView mImageView;
    DisplayImages images;

    public LoadImages(String urlString, ImageView mImageView) {
        this.urlString = urlString;
        this.mImageView = mImageView;
    }

    public void run() {

        if(!ImageViewReused(urlString, mImageView)){
            Bitmap bitmap = DownloadFromUrl(urlString);

            Bitmap mBitmapMask = mCommonMethod.makeMaskImageCrop(bitmap, R.drawable.image_thumb_mask, R.drawable.image_thumb);

            //TODO to mask image then bitmap pass
            addBitmapToDiskCache(urlString, mBitmapMask);

            DisplayImages images = new DisplayImages(urlString, mImageView, mBitmapMask);
            ((Activity) mImageView.getContext()).runOnUiThread(images);
        }
    }
}

class DisplayImages implements Runnable {
    Bitmap bitmap;
    String urlString;
    ImageView mImageView;

    public DisplayImages(String urlString, ImageView mImageView, Bitmap bitmap) {
        this.urlString = urlString;
        this.mImageView = mImageView;
        this.bitmap = bitmap;
    }

    public void run() {

        if(!ImageViewReused(urlString, mImageView)){
            if (bitmap != null)
                mImageView.setImageBitmap(bitmap);
            else
                mImageView.setImageResource(default_icon);
        }
    }
}

private Bitmap DownloadFromUrl(String urlString) {
    return decodeBitmapFromStream(urlString, getReqiredWidth(), getRequiredHeight());
}

private void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    synchronized (mMemoryCache) {
        if (mMemoryCache.get(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }
}
private Bitmap getBitmapFromMemCache(String key) {
    Bitmap bitmap = mMemoryCache.get(key);
    if(bitmap == null){
        bitmap = getBitmapFromDiskCache(key);
    }
    return bitmap;
}

private void addBitmapToDiskCache(String key, Bitmap bitmap) {
    synchronized (mDiskLruImageCache) {
        if (!mDiskLruImageCache.containsKey(String.valueOf(key.hashCode()))) {
            mDiskLruImageCache.put(String.valueOf(key.hashCode()), bitmap);
            addBitmapToMemoryCache(key, bitmap);
        }
    }
}

private Bitmap getBitmapFromDiskCache(String key) {
    return mDiskLruImageCache.getBitmap(String.valueOf(key.hashCode()));
}


private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    inSampleSize = Math.min(width/reqWidth, height/reqHeight);

    return inSampleSize;
}

private static Bitmap decodeBitmapFromStream(String urlString, int reqWidth, int reqHeight) {

    URL url = null;
    InputStream is = null;
    try {
        url = new URL(urlString);
        is = (InputStream) url.getContent();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // As InputStream can be used only once we have to regenerate it again.
    try {
        is = (InputStream) url.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return  BitmapFactory.decodeStream(is, null, options);
}

public int getRequiredHeight() {
    return requiredHeight;
}

public void setRequiredHeight(int longest, int requiredHeight) {
    this.requiredHeight = requiredHeight > longest ? longest : requiredHeight;
}

public int getReqiredWidth() {
    return requiredWidth;
}

public void setReqiredWidth(int longest, int requiredWidth) {
    this.requiredWidth = requiredWidth > longest ? longest : requiredWidth; 
}

public void clearCacheMemory() {
    if(mMemoryCache.size() > 0){
        mMemoryCache.evictAll();
    }
}

public void clearDiskMemory() {
    mDiskLruImageCache.clearCache();
}
}

希望你能从上面的代码中得到一些想法和提示..