单一职责之ImageLoader(二)

前端之家收集整理的这篇文章主要介绍了单一职责之ImageLoader(二)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
public class ImageCache {
    //图片缓存
    LruCache<String,Bitmap> mImageCache;
    public ImageCache(){

    }
    private void initImageCache(){
        //计算可用的最大内存
        final int maxMemory = (int)(Runtime.getRuntime().maxMemory()/1024);
        //取四分之一内存作为缓存
        final int cacheSize = maxMemory/4;
        mImageCache = new LruCache<String,Bitmap>(cacheSize){
            @Override
            protected int sizeOf(String key,Bitmap value) {
                return value.getRowBytes()*value.getHeight()/1024;
            }
        };
    }
    public void put(String url,Bitmap bitmap){
        mImageCache.put(url,bitmap);
    }

    public Bitmap get(String url){
        return mImageCache.get(url);
    }
}


package gac.com.chapter1.version2;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;
import android.widget.ImageView;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** * Created by gacmy on 2016/9/10. */
public class ImageLoader {
    //图片缓存
    ImageCache mImageCache = new ImageCache();
    //线程池
    ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().
            availableProcessors());



    //显示网络加载的图片 调用一次都会开启线程去下载 并且显示
    public void displayImage(final String url,final ImageView imageView){
        imageView.setTag(url);
        mExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                Bitmap bitmap = downloadImage(url);
                if(bitmap == null){
                    return ;
                }
                if(imageView.getTag().equals(url)){
                    imageView.setImageBitmap(bitmap);
                }
                mImageCache.put(url,bitmap);
            }
        });
    }

    public Bitmap downloadImage(String imageUrl){
        Bitmap bitmap = null;
        try {
            URL url = new URL(imageUrl);
            final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}

现在代码一分为二清晰了,但是Android内存有限,每次重新启动后原来加载的图片就会丢失,所以需要改进 缓存到本地

原文链接:https://www.f2er.com/javaschema/283660.html

猜你在找的设计模式相关文章