欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三级缓存图片类

程序员文章站 2022-07-02 09:46:06
...
package com.azy.xiaolong.news.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.util.LruCache;

public class BitmapLoad {

    private static LruCache<String, Bitmap> cache;
    private static File cachePath;
    private BitmapCallback callback;
    public BitmapLoad(Context context) {
        int size=(int) (Runtime.getRuntime().maxMemory()/8);
        if(cache==null){
            cache=new LruCache<String, Bitmap>(size){
                @Override
                protected int sizeOf(String key, Bitmap value) {
                    return value.getRowBytes()*value.getHeight();
                }
            };
        }

        if(cachePath==null){
            cachePath=context.getExternalCacheDir();
            if(!cachePath.exists()){
                cachePath.mkdirs();
            }
        }
    }

    //加载图片
    @SuppressWarnings("unused")
    public Bitmap LoadBitmap(String url, BitmapCallback callback) {
        this.callback = callback;
        // 从缓存中取图片
        Bitmap bitmap = null;
        bitmap = getBitmapToCache(url);
        if (bitmap != null) {
            return bitmap;
        }
        // 从SD卡内存中取图片
        bitmap = getBitmapToSdcard(url);
        if (bitmap != null) {
            return bitmap;
        }

        // 从网络下载
        getBitmapNet(url, callback);
        return null;
    }

    // 从缓存中取图片
    private Bitmap getBitmapToCache(String url) {
        return cache.get(url);
    }

    // 从缓存中存图片
    private void putBitmapToCache(String url, Bitmap bitmap) {
        cache.put(url, bitmap);
    }

    // 从SD卡内存中取图片
    private Bitmap getBitmapToSdcard(String url) {
        String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
        File file = new File(cachePath, fileName);
        if (file.exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            putBitmapToCache(url, bitmap);
            return bitmap;
        }
        return null;

    }

    // 从SD卡内存中存图片
    private void putBitmapToSdcard(String url, Bitmap bitmap) {
        String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
        File file = new File(cachePath, fileName);
        OutputStream os;
        try {
            os = new FileOutputStream(file);
            bitmap.compress(CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 下载完成后回调的接口
    public interface BitmapCallback {
        public void BitmapOk(String str, Bitmap bitmap);

        public void BitmapError(String url);
    }

    // 从网络下载
    @SuppressLint("NewApi")
    private void getBitmapNet(String url, BitmapCallback callback) {
        BitmapAsyn2 asyn = new BitmapAsyn2();
        if (Build.VERSION.SDK_INT >= 11) {
            asyn.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
        } else {
            asyn.execute(url);
        }

    }

    // 异步任务类
    class BitmapAsyn2 extends AsyncTask<String, Void, Bitmap> {
        String url;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            this.url = params[0];
            InputStream is = HttpClientUtil
                    .httpGet2InputStream(params[0], null);
            if (is != null) {
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                if (bitmap != null) {
                    putBitmapToCache(url, bitmap);
                    putBitmapToSdcard(url, bitmap);
                    try {
                        is.close();
                        return bitmap;
                    } catch (IOException e) {
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            if (result != null) {
                callback.BitmapOk(url, result);
            } else {
                callback.BitmapError(url);
            }
        }

    }

}