三级缓存

本文章可以学到:

1、图片压缩

2、图片异步加载

3、内存缓存

4、本地缓存

5、网络缓存

6、MD5加密


代码下载:http://download.csdn.net/detail/runingling/9674550


MyBitmapUtils //工具集

package com.example.liangshaoteng.mycache.Utils;

import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;

import com.example.liangshaoteng.mycache.R;

/**
 * Created by LiangShaoTeng on 2016/10/26.
 */

public class MyBitmapUtils {

    private final MemoryCacheUtils memoryCacheUtils;
    private final LocalCacheUtils localCacheUtils;
    private final NetCacheUtils netCacheUtils;
    private Bitmap bitmap;

    public MyBitmapUtils() {
        //内存
        memoryCacheUtils = new MemoryCacheUtils();
        //本地
        localCacheUtils = new LocalCacheUtils();
        //网络
        netCacheUtils = new NetCacheUtils(memoryCacheUtils,localCacheUtils);
    }

    public void disPlay(ImageView imageView,String url){

        imageView.setImageResource(R.mipmap.ic_launcher);


        //内存缓存
        bitmap = memoryCacheUtils.getImageBitmapMemory(url);
        if(bitmap !=null){
            imageView.setImageBitmap(bitmap);

            System.out.println("从内存获取图片");
            return;
        }



        //本地缓存
        bitmap = localCacheUtils.getImageBitmapLocal(url);
        if(bitmap !=null){
            imageView.setImageBitmap(bitmap);
            //从本地获取图片存入内存
            memoryCacheUtils.setBitmapToMemory(url, bitmap);

            System.out.println("从本地获取图片");
            return;
        }


        //网络存储
        netCacheUtils.getBitmapRequest(imageView,url);

    }
}


MemoryCacheUtils //内存缓存


package com.example.liangshaoteng.mycache.Utils;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.LruCache;

/**
 * Created by LiangShaoTeng on 2016/10/26.
 */

public class MemoryCacheUtils {

    private final LruCache mMemoryCache;

    public MemoryCacheUtils() {
        //获取手机允许最大内存的1/8,如果超过指定内存,就开始回收
        long maxMemory = Runtime.getRuntime().maxMemory() / 8;
        //需要传入允许的内存最大值,虚拟机默认内存16M,真机不一定相同
        mMemoryCache = new LruCache((int) maxMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //获取对象的大小
                int byteCount = value.getByteCount();
                return byteCount;
            }
        };


    }

    public Bitmap getImageBitmapMemory(String url) {
        //通过url的key值查找图片
        try {
            String encode = MD5Encoder.encode(url);
            Bitmap bitmap = mMemoryCache.get(encode);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public void setBitmapToMemory(String url, Bitmap bitmap) {
        try {
            String encode = MD5Encoder.encode(url);
            mMemoryCache.put(encode, bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


LocalCacheUtils //本地缓存



package com.example.liangshaoteng.mycache.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream;

/**
 * Created by LiangShaoTeng on 2016/10/26.
 */

public class LocalCacheUtils {

    private static final String CACHE_PATH=Environment.getExternalStorageDirectory().getAbsolutePath()+"/cache";

    public Bitmap getImageBitmapLocal(String url) {

        try {
            String encode = MD5Encoder.encode(url);

            File file=new File(CACHE_PATH,encode);

            //decodeStream 解码输入流的位图
            //FileInputStream 用于读取本地文件中的字节数据,继承自InputStream类
            Bitmap bitmap= BitmapFactory.decodeStream(new FileInputStream(file));
            return bitmap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setBitmapToLocal(String url,Bitmap bitmap){

        try {
            String encode = MD5Encoder.encode(url);
            File file=new File(CACHE_PATH,encode);

            File parentFile = file.getParentFile();
            if(!parentFile.exists()){
                parentFile.mkdir();
            }

            //bitmap.compress(CompressFormat,quality,)
            //CompressFormat 压缩格式
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}


NetCacheUtils //网络缓存



package com.example.liangshaoteng.mycache.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by LiangShaoTeng on 2016/10/26.
 */

public class NetCacheUtils {
    MemoryCacheUtils memoryCacheUtils;
    LocalCacheUtils localCacheUtils;
    private HttpURLConnection urlConnection;

    public NetCacheUtils(MemoryCacheUtils memoryCacheUtils, LocalCacheUtils localCacheUtils) {
        this.localCacheUtils=localCacheUtils;
        this.memoryCacheUtils=memoryCacheUtils;
    }

    public void getBitmapRequest(ImageView imageView, String url) {
        new BitmapTask().execute(imageView,url);

    }

    class BitmapTask extends AsyncTask{

        private ImageView imageView;
        private String url;

        @Override
        protected Bitmap doInBackground(Object... objects) {
            imageView = (ImageView) objects[0];
            url =  (String) objects[1];
            return downLoadBitmap(url);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if(bitmap!=null){
                imageView.setImageBitmap(bitmap);

                System.out.println("从網絡获取图片");
                //存入内存
                memoryCacheUtils.setBitmapToMemory(url,bitmap);
                //存入本地
                localCacheUtils.setBitmapToLocal(url,bitmap);
            }

            super.onPostExecute(bitmap);
        }
    }

    private Bitmap downLoadBitmap(String url) {
        try {
            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setRequestMethod("GET");

            if(urlConnection.getResponseCode()== HttpURLConnection.HTTP_OK){

                BitmapFactory.Options bitmapFactory=new BitmapFactory.Options();
                bitmapFactory.inSampleSize = 2;//宽高压缩为原来的1/2
                bitmapFactory.inPreferredConfig= Bitmap.Config.ARGB_4444;
                /*Rect rect=new Rect();
                rect.contains(5,500,5,5);*/
                Bitmap bimap=BitmapFactory.decodeStream(urlConnection.getInputStream(),null ,bitmapFactory);
                return bimap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            urlConnection.disconnect();
        }

        return null;
    }

}

MD5Encoder //MD5



package com.example.liangshaoteng.mycache.Utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by LiangShaoTeng on 2016/10/26.
 */

public class MD5Encoder {
    public static String encode(String string) throws Exception {
        byte[] hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}



你可能感兴趣的:(Android)