add Bitmap To Memory Cache LruCache - Android App

Android examples for App:Cache

Description

add Bitmap To Memory Cache LruCache

Demo Code


//package com.book2s;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class Main {
    private static LruCache<String, Bitmap> mMemoryCache;

    public static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (mMemoryCache == null)
            initMemoryCache();//from   ww w  . j  a  v  a 2s .  c o m
        if (getBitmapFromMemCache(key) == null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    private static void initMemoryCache() {
        if (mMemoryCache == null) {
            int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

            int cacheSize = maxMemory / 2;
            mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {

                    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
                }
            };
        }
    }

    public static Bitmap getBitmapFromMemCache(String key) {
        if (mMemoryCache == null)
            initMemoryCache();
        return mMemoryCache.get(key);
    }
}

Related Tutorials