三级缓存

  1. //定义的硬盘缓存工具类有添加和取出方法
    public class Hard_disk_cache {
        public  final String cach= Environment.getExternalStorageDirectory().getAbsolutePath();
            //此为硬盘缓存的方法
    
        public Bitmap getBitmap(String url){
            File file=new File(cach,url);
    
            try {
           Bitmap     bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
                return bitmap;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }
        public void put(String url, Bitmap bitmap) {
            try {
    
    
                File file = new File(cach, url);
    
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {// 如果文件夹不存在, 创建文件夹
                    parentFile.mkdirs();
                }
    
                // 将图片保存在本地
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                        new FileOutputStream(file));
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }}
  2.  
  • //定义的内存缓存工具类
    public class Memory_cache {
        private long MAX;   //定义缓存最大值
        private LruCache<String,Bitmap> lruCache;
    
        public Memory_cache() {
                //获取当前应用的最大缓存值 /8 
            MAX = Runtime.getRuntime().maxMemory() / 8;
            lruCache=new LruCache<String, Bitmap>((int) MAX){
                @Override
                protected int sizeOf(String key, Bitmap value) {
                    return value.getRowBytes();
                }
            };
        }
            //设置 添加方法
        public void putBitmap(String url, Bitmap bitmap) {
            //通过key value的形式存bitmap
            lruCache.put(url, bitmap);
        }
    
    
        //取出方法  从内存取出来
        public  Bitmap  getBitmap(String url){
            Bitmap bitmap= lruCache.get(url);
            return bitmap;
        }
    }
  • 3
  • //定义的图片缓存解析
public class Caching_request {
    private Hard_disk_cache hard_disk_cache;
    private Memory_cache memory_cache;
    //定义成员方法 并利用构造进行赋值
         public Caching_request(Hard_disk_cache hard_disk_cache, Memory_cache memory_cache) {
        this.hard_disk_cache = hard_disk_cache;
        this.memory_cache = memory_cache;

         }
//定义方法进行URL 查找图片并启动网络请求类

    public void getBitmapFromNet(ImageView ivPic, String url) {
        new BitmapTask().execute(ivPic, url);// 启动AsyncTask,
        // 参数会在doInbackground中获取
    }

 //这边进行网络请求图片类进行3级缓存
    class BitmapTask extends AsyncTask<Object, Void, Bitmap> {

        private ImageView ivPic;
        private String url;

        /**
         * 后台耗时方法在此执行, 子线程
         */
        @Override
        protected Bitmap doInBackground(Object... params) {
            ivPic = (ImageView) params[0];
            url = (String) params[1];

            ivPic.setTag(url);// 将url和imageview绑定

            return downloadBitmap(url);
        }

        /**
         * 更新进度, 主线程
         */
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        /**
         * 耗时方法结束后,执行该方法, 主线程
         */
        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                String bindUrl = (String) ivPic.getTag();

                if (url.equals(bindUrl)) {// 确保图片设定给了正确的imageview
                    ivPic.setImageBitmap(result);
                    hard_disk_cache.put(url, result);// 将图片保存在本地
                    memory_cache.putBitmap(url, result);// 将图片保存在内存
                }
            }
        }
    }

    /**
     * 下载图片
     *
     * @param url
     * @return
     */
    private Bitmap downloadBitmap(String url) {

        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();

            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");
            conn.connect();

            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = conn.getInputStream();

                //图片压缩处理
                BitmapFactory.Options option = new BitmapFactory.Options();
                option.inSampleSize = 2;//宽高都压缩为原来的二分之一, 此参数需要根据图片要展示的大小来确定
                option.inPreferredConfig = Bitmap.Config.RGB_565;//设置图片格式

                Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, option);
                return bitmap;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

        return null;
    }

}

4

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.button2)
    Button button2;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.button3)
    Button button3;
    private Hard_disk_cache hard_disk_cache;
    private Memory_cache memory_cache;
    private Caching_request caching_request;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //初始化定义的内存缓存和硬盘缓存
        hard_disk_cache = new Hard_disk_cache();
        memory_cache = new Memory_cache();
        caching_request = new Caching_request(hard_disk_cache, memory_cache);

    }
    String url = "https://ww1.sinaimg.cn/large/0065oQSqly1ft5q7ys128j30sg10gnk5.jpg";
    @OnClick({R.id.button, R.id.button2, R.id.button3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button:
                //此方法就是我们定义的启动AsyncTask定义的第一个参数就是要复制的图片
                caching_request.getBitmapFromNet(image,url);
                break;
            case R.id.button2:
                //返回Bitmap对象 此处调用的内存缓存工具类对象中的获取方法
                Bitmap bitmaps = memory_cache.getBitmap(url);
                image2.setImageBitmap(bitmaps);
                break;
            case R.id.button3:

                //返回Bitmap对象    此处调用的硬盘缓存工具类对象中的获取方法 
                Bitmap bitmap = hard_disk_cache.getBitmap(url);
                image3.setImageBitmap(bitmap);
                break;
        }
    }
}
<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
//权限添加

猜你喜欢

转载自blog.csdn.net/qq_42046338/article/details/81086861