大量加载网络图片,使用一二级缓存,数据自行添加,复制可用

/**
 * 在内存中存储图片(一级缓存), 采用了1map来缓存图片代码如下:
 */

public class MemoryCache {
    // 最大的缓存数
    private static final int MAX_CACHE_CAPACITY = 30;
    //Map软引用的Bitmap对象, 保证内存空间足够情况下不会被垃圾回收
    private HashMap<String, SoftReference<Bitmap>> mCacheMap =
            new LinkedHashMap<String, SoftReference<Bitmap>>() {
                private static final long serialVersionUID = 1L;
                //当缓存数量超过规定大小(返回true)会清除最早放入缓存的
                protected boolean removeEldestEntry(
                        Map.Entry<String,SoftReference<Bitmap>> eldest){
                    return size() > MAX_CACHE_CAPACITY;};
            };

    /**
     * 从缓存里取出图片
     * @param id
     * @return 如果缓存有,并且该图片没被释放,则返回该图片,否则返回null
     */
    public Bitmap get(String id){
        if(!mCacheMap.containsKey(id)) return null;
        SoftReference<Bitmap> ref = mCacheMap.get(id);
        return ref.get();
    }

    /**
     * 将图片加入缓存
     * @param id
     * @param bitmap
     */
    public void put(String id, Bitmap bitmap){
        mCacheMap.put(id, new SoftReference<Bitmap>(bitmap));
    }
    /**
     * 清除所有缓存
     */
    public void clear() {
        try {
            for(Map.Entry<String,SoftReference<Bitmap>>entry :mCacheMap.entrySet())
            {    SoftReference<Bitmap> sr = entry.getValue();
                if(null != sr) {
                    Bitmap bmp = sr.get();
                    if(null != bmp) bmp.recycle();
                }
            }
            mCacheMap.clear();
        } catch (Exception e) {
            e.printStackTrace();}
    }
}
 
/**
 * 在磁盘中缓存图片(二级缓存),代码如下
 */

public class FileCache {
    //缓存文件目录
    private File mCacheDir;
    /**
     * 创建缓存文件目录,如果有SD卡,则使用SD,如果没有则使用系统自带缓存目录
     * @param context
     * @param cacheDir 图片缓存的一级目录
     */
    public FileCache(Context context, Uri cacheDir, String dir){
        if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
//        mCacheDir = new File(cacheDir, dir);
            mCacheDir = new File (context.getExternalCacheDir(),"my_image.jpg");
      else
        mCacheDir = context.getCacheDir();// 如何获取系统内置的缓存存储路径
        if(!mCacheDir.exists())  mCacheDir.mkdirs();
    }
    public File getFile(String url){
        File f=null;
        try {
//url进行编辑,解决中文路径问题
            String filename = URLEncoder.encode(url,"utf-8");
            f = new File(mCacheDir, filename);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return f;
    }
    public void clear(){//清除缓存文件
        File[] files = mCacheDir.listFiles();
        for(File f:files)f.delete();
    }
}

 
/**
 * 编写异步加载组件AsyncImageLoader
 */

public class AsyncImageLoader {
    private MemoryCache mMemoryCache;//内存缓存
    private FileCache mFileCache;//文件缓存
    private ExecutorService mExecutorService;//线程池
    //记录已经加载图片的ImageView
    private Map<ImageView, String> mImageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    //保存正在加载图片的url
    private List<LoadPhotoTask> mTaskQueue = new ArrayList<LoadPhotoTask>();
    /**
     * 默认采用一个大小为5的线程池
     * @param context
     * @param memoryCache 所采用的高速缓存
     * @param fileCache 所采用的文件缓存
     */
    public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) {
        mMemoryCache = memoryCache;
        mFileCache = fileCache;
        mExecutorService = Executors.newFixedThreadPool(5);//建立一个容量为5的固定尺寸的线程池(最大正在运行的线程数量)
    }
    /**
     * 根据url加载相应的图片
     * @param url
     * @return 先从一级缓存中取图片有则直接返回,如果没有则异步从文件(二级缓存)中取,如果没有再从网络端获取
     */
    public Bitmap loadBitmap(ImageView imageView, String url) {
        //先将ImageView记录到Map,表示该ui已经执行过图片加载了
        mImageViews.put(imageView, url);
        Bitmap bitmap = mMemoryCache.get(url);//先从一级缓存中获取图片
        if(bitmap == null) {
            enquequeLoadPhoto(url, imageView);//再从二级缓存和网络中获取
        }
        return bitmap;
    }

    /**
     * 加入图片下载队列
     * @param url
     */
    private void enquequeLoadPhoto(String url, ImageView imageView) {
        //如果任务已经存在,则不重新添加
        if(isTaskExisted(url))
            return;
        LoadPhotoTask task = new LoadPhotoTask(url, imageView);
        synchronized (mTaskQueue) {
            mTaskQueue.add(task);//将任务添加到队列中
        }
        mExecutorService.execute(task);//向线程池中提交任务,如果没有达到上限(5),则运行否则被阻塞
    }

    /**
     * 判断下载队列中是否已经存在该任务
     * @param url
     * @return
     */
    private boolean isTaskExisted(String url) {
        if(url == null)
            return false;
        synchronized (mTaskQueue) {
            int size = mTaskQueue.size();
            for(int i=0; i<size; i++) {
                LoadPhotoTask task = mTaskQueue.get(i);
                if(task != null && task.getUrl().equals(url))
                    return true;
            }
        }
        return false;
    }

    /**
     * 从缓存文件或者网络端获取图片
     * @param url
     */
    private Bitmap getBitmapByUrl(String url) {
        File f = mFileCache.getFile(url);//获得缓存图片路径
        Bitmap b = ImageUtil.decodeFile(f);//获得文件的Bitmap信息
        if (b != null)//不为空表示获得了缓存的文件
            return b;
        return ImageUtil.loadBitmapFromWeb(url, f);//同网络获得图片
    }

    /**
     * 判断该ImageView是否已经加载过图片了(可用于判断是否需要进行加载图片)
     * @param imageView
     * @param url
     * @return
     */
    private boolean imageViewReused(ImageView imageView, String url) {
        String tag = mImageViews.get(imageView);
        if (tag == null || !tag.equals(url))
            return true;
        return false;
    }

    private void removeTask(LoadPhotoTask task) {
        synchronized (mTaskQueue) {
            mTaskQueue.remove(task);
        }
    }

    class LoadPhotoTask implements Runnable {
        private String url;
        private ImageView imageView;
        LoadPhotoTask(String url, ImageView imageView) {
            this.url = url;
            this.imageView = imageView;
        }

        @Override
        public void run() {
            if (imageViewReused(imageView, url)) {//判断ImageView是否已经被复用
                removeTask(this);//如果已经被复用则删除任务
                return;
            }
            Bitmap bmp = getBitmapByUrl(url);//从缓存文件或者网络端获取图片
            mMemoryCache.put(url, bmp);// 将图片放入到一级缓存中
            if (!imageViewReused(imageView, url)) {//ImageView未加图片则在ui线程中显示图片
                BitmapDisplayer bd = new BitmapDisplayer(bmp, imageView, url);
                Activity a = (Activity) imageView.getContext();
                a.runOnUiThread(bd);//UI线程调用bd组件的run方法,实现为ImageView控件加载图片
            }
            removeTask(this);//从队列中移除任务
        }
        public String  getUrl() {
            return url;
        }
    }

    /**
     *
     *UI线程中执行该组件的run方法
     */
    class BitmapDisplayer implements Runnable {
        private Bitmap bitmap;
        private ImageView imageView;
        private String url;
        public BitmapDisplayer(Bitmap b, ImageView imageView, String url) {
            bitmap = b;
            this.imageView = imageView;
            this.url = url;
        }
        public void run() {
            if (imageViewReused(imageView, url))
                return;
            if (bitmap != null)
                imageView.setImageBitmap(bitmap);
        }
    }

    /**
     * 释放资源
     */
    public void destroy() {
        mMemoryCache.clear();
        mMemoryCache = null;
        mImageViews.clear();
        mImageViews = null;
        mTaskQueue.clear();
        mTaskQueue = null;
        mExecutorService.shutdown();
        mExecutorService = null;
    }
}

 
/**
 * 工具类ImageUtil
 */

public class ImageUtil {
    /**
     * 从网络获取图片,并缓存在指定的文件中
     * @param url 图片url
     * @param file 缓存文件
     * @return
     */
    public static Bitmap loadBitmapFromWeb(String url, File file) {
        HttpURLConnection conn = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            Bitmap bitmap = null;
            URL imageUrl = new URL(url);
            conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            is = conn.getInputStream();
            os = new FileOutputStream(file);
            copyStream(is, os);//将图片缓存到磁盘中
            bitmap = decodeFile(file);
            return bitmap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                if(os != null) os.close();
                if(is != null) is.close();
                if(conn != null) conn.disconnect();
            } catch (IOException e) {    }
        }
    }

    public static Bitmap decodeFile(File f) {
        try {
            return BitmapFactory.decodeStream(new FileInputStream(f), null, null);
        } catch (Exception e) { }
        return null;
    }
    private  static void copyStream(InputStream is, OutputStream os) {
        final int buffer_size = 1024;
        try {
            byte[] bytes = new byte[buffer_size];
            for (;;) {
                int count = is.read(bytes, 0, buffer_size);
                if (count == -1)
                    break;
                os.write(bytes, 0, count);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

 
public class ListViewAdapter extends BaseAdapter {
    private Activity mActivity;
    List<GrphData> list=new ArrayList<GrphData>();
    private AsyncImageLoader imageLoader;//异步组件

    public ListViewAdapter(Activity mActivity, List<GrphData> list) {
        this.mActivity=mActivity;
        this.list=list;
        MemoryCache mcache=new MemoryCache();//内存缓存
        File db;
        Uri data;
        if (Build.VERSION.SDK_INT>=24){
            db= new File(mActivity.getExternalCacheDir(),"jereh_cache");
            data = FileProvider.getUriForFile(mActivity, "com.athis.app.provider", db);
        }else {
            db = new File(mActivity.getExternalCacheDir(),"jereh_cache");
            data = Uri.fromFile(db);
        }

        FileCache fcache=new FileCache(mActivity, data,"news_img");//文件缓存
        imageLoader = new AsyncImageLoader(mActivity, mcache,fcache);


    }
    public int getCount() {
        return list.size();
    }
    public Object getItem(int position) {
        return list.get(position);
    }
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        View view;
        if(convertView==null){
            view=View.inflate(mActivity, R.layout.hyph_item_layout,null);
            vh=new ViewHolder();
            vh.shu=view.findViewById(R.id.phtv);
            vh.tou=view.findViewById(R.id.touxaingiv);
            vh.name=view.findViewById(R.id.nametv);
            vh.cishu=view.findViewById(R.id.cishutv);
            view.setTag(vh);
        }else{
            view=convertView;
            vh=(ViewHolder)convertView.getTag();
        }
        vh.shu.setText(list.get(position).getI());
        vh.cishu.setText(list.get(position).getCount());
        vh.name.setText(list.get(position).getNickname());
        //异步加载图片,先从一级缓存、再二级缓存、最后网络获取图片
        Bitmap bmp = imageLoader.loadBitmap(vh.tou,list.get(position).getAvatar());
        if(bmp == null) {
            vh.tou.setImageResource(R.drawable.default_avatar);
        } else {
            vh.tou.setImageBitmap(bmp);
        }
        return view;
    }
    private class ViewHolder{
        TextView shu;
        CircleImageView tou;
        TextView name;
        TextView cishu;
    }
    public void destroy() {
        imageLoader.destroy();
    }
}

 
/**
 * Activity 中调用
 */
ListViewAdapter adapter=new ListViewAdapter(mActivity, list);
lv.setAdapter(adapter);

/**
 * 退出销毁
 */
@Overrideprotected void onDestroy() { super.onDestroy(); adapter.destroy();}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值