29 三级缓存案例

LRU:least rencently used 最近最少使用

LruCache 会在内存不足的杀死最近不常用的资源

package com.qf.sxy.day30_cache.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;

import com.qf.sxy.day30_cache.asynctask.DownLoadImage;
import com.qf.sxy.day30_cache.interfacecallback.ImageCallBack;

/**
 * Created by sxy on 2016/9/30.
 * 进行缓存和处理图片
 */
public class LruCacheUtils {

    //Lru缓存
    private LruCache<String,Bitmap> cache;
    private  Context context;
    private ImageCallBack imageCallBack;

    public LruCacheUtils(Context context,ImageCallBack imageCallBack){

        this.context = context;
        this.imageCallBack = imageCallBack;
        //运行时内存的1/8大小
        long maxMemory = Runtime.getRuntime().maxMemory();
        int maxSize =(int)(maxMemory/8);
        cache = new LruCache<String,Bitmap>(maxSize){

            //返回图片的大小
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount();
            }
        };
    }


    //获取图片
    public Bitmap getBitmap(String key){

        //从缓存中找
        Bitmap bitmap = cache.get(key);
        if (bitmap!=null){
            Log.e("AA","==Lru==");
            return bitmap;
        }else{
            //从Sd找
            bitmap = Utils.getBitmapFromSD(key,context);
            if (bitmap!=null){
                Log.e("AA","==SD==");
                //存到缓存
                cache.put(key,bitmap);
                return bitmap;
            }else{
                Log.e("AA","==NET==");
                //下载图片
                new DownLoadImage(context,cache,imageCallBack).execute(key);
            }
        }


        return null;
    }

}

posted on 2016-10-01 20:05  木鱼哥  阅读(157)  评论(0编辑  收藏  举报

导航