标签:
内存缓存技术对那些大量占用应用程序宝贵内存的图片提供了高速訪问的方法。当中最核心的类是LruCache 。这个类非常适合用来缓存图片,它的主要算法原理是把近期使用的对象用强引用存储在 LinkedHashMap 中,并且把近期最少使用的对象在缓存值达到预设定值之前从内存中移除。LruCache 是在support-v4中才引入的,在引入LruCache 之前。Google建议的是使用软引用或弱引用 (SoftReference or WeakReference)来进行内存缓存。可是从Android 2.3開始,GC算法改动,软引用与弱引用相同会优先被GC回收。所以这样的方法也就没有太高的使用价值了,如今网上非常多还在继续使用SoftReference 和WeakReference的文章。大多都是过时的文章,建议大家跟上党的步伐,与时俱进。
这个平衡点常常须要非常多经验和測试来决定。
使用LruCache非常easy:
private LruCache<String, Bitmap> mMemoryCaches; // 获取应用内存 int maxMemory = (int) Runtime.getRuntime().maxMemory(); // 分配cache int cacheSize = maxMemory / 10; mMemoryCaches = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); } }; // 从LruCache获取中获取缓存对象 public Bitmap getBitmapFromMemoryCaches(String url) { return mMemoryCaches.get(url); } // 添加缓存对象到LruCache public void addBitmapToMemoryCaches(String url,Bitmap bitmap) { if (getBitmapFromMemoryCaches(url) == null) { mMemoryCaches.put(url, bitmap); } }
。。尼玛。
@Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_IDLE) { mImageLoader.loadImages(mStart, mEnd); } else { mImageLoader.cancelAllTasks(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { mStart = firstVisibleItem; mEnd = firstVisibleItem + visibleItemCount; if (mFirstFlag && visibleItemCount > 0) { mImageLoader.loadImages(mStart, mEnd); mFirstFlag = false; } }
public void loadImages(int start, int end) { for (int i = start; i < end; i++) { String url = Images.IMAGE_URLS[i]; Bitmap bitmap = getBitmapFromMemoryCaches(url); if (bitmap == null) { ASyncDownloadImage task = new ASyncDownloadImage(url); mTasks.add(task); task.execute(url); } else { ImageView imageView = (ImageView) mListView.findViewWithTag(url); imageView.setImageBitmap(bitmap); } } }
private static Bitmap getBitmapFromUrl(String urlString) { Bitmap bitmap; InputStream is = null; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); is = new BufferedInputStream(conn.getInputStream()); bitmap = BitmapFactory.decodeStream(is); conn.disconnect(); return bitmap; } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } } return null; }
class ASyncDownloadImage extends AsyncTask<String, Void, Bitmap> { private String url; public ASyncDownloadImage(String url) { this.url = url; } @Override protected Bitmap doInBackground(String... params) { url = params[0]; Bitmap bitmap = getBitmapFromUrl(url); if (bitmap != null) { addBitmapToMemoryCaches(url, bitmap); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); ImageView imageView = (ImageView) mListView.findViewWithTag(url); if (imageView != null && bitmap != null) { imageView.setImageBitmap(bitmap); } mTasks.remove(this); } }
package com.imooc.listviewacyncloader; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.LruCache; import android.widget.ImageView; import android.widget.ListView; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashSet; import java.util.Set; public class ImageLoaderWithCaches { private Set<ASyncDownloadImage> mTasks; private LruCache<String, Bitmap> mMemoryCaches; private ListView mListView; public ImageLoaderWithCaches(ListView listview) { this.mListView = listview; mTasks = new HashSet<>(); int maxMemory = (int) Runtime.getRuntime().maxMemory(); int cacheSize = maxMemory / 10; mMemoryCaches = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); } }; } public void showImage(String url, ImageView imageView) { Bitmap bitmap = getBitmapFromMemoryCaches(url); if (bitmap == null) { imageView.setImageResource(R.drawable.ic_launcher); } else { imageView.setImageBitmap(bitmap); } } public Bitmap getBitmapFromMemoryCaches(String url) { return mMemoryCaches.get(url); } public void addBitmapToMemoryCaches(String url,Bitmap bitmap) { if (getBitmapFromMemoryCaches(url) == null) { mMemoryCaches.put(url, bitmap); } } public void loadImages(int start, int end) { for (int i = start; i < end; i++) { String url = Images.IMAGE_URLS[i]; Bitmap bitmap = getBitmapFromMemoryCaches(url); if (bitmap == null) { ASyncDownloadImage task = new ASyncDownloadImage(url); mTasks.add(task); task.execute(url); } else { ImageView imageView = (ImageView) mListView.findViewWithTag(url); imageView.setImageBitmap(bitmap); } } } private static Bitmap getBitmapFromUrl(String urlString) { Bitmap bitmap; InputStream is = null; try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); is = new BufferedInputStream(conn.getInputStream()); bitmap = BitmapFactory.decodeStream(is); conn.disconnect(); return bitmap; } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } } return null; } public void cancelAllTasks() { if (mTasks != null) { for (ASyncDownloadImage task : mTasks) { task.cancel(false); } } } class ASyncDownloadImage extends AsyncTask<String, Void, Bitmap> { private String url; public ASyncDownloadImage(String url) { this.url = url; } @Override protected Bitmap doInBackground(String... params) { url = params[0]; Bitmap bitmap = getBitmapFromUrl(url); if (bitmap != null) { addBitmapToMemoryCaches(url, bitmap); } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); ImageView imageView = (ImageView) mListView.findViewWithTag(url); if (imageView != null && bitmap != null) { imageView.setImageBitmap(bitmap); } mTasks.remove(this); } } }
package com.imooc.listviewacyncloader; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import java.util.List; public class MyAdapterUseCaches extends BaseAdapter implements AbsListView.OnScrollListener { private LayoutInflater mInflater; private List<String> mData; private ImageLoaderWithCaches mImageLoader; private int mStart = 0, mEnd = 0; private boolean mFirstFlag; public MyAdapterUseCaches(Context context, List<String> data, ListView listView) { this.mData = data; mInflater = LayoutInflater.from(context); mImageLoader = new ImageLoaderWithCaches(listView); mImageLoader.loadImages(mStart, mEnd); mFirstFlag = true; listView.setOnScrollListener(this); } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { String url = mData.get(position); ViewHolder viewHolder = null; if (convertView == null) { viewHolder = new ViewHolder(); convertView = mInflater.inflate(R.layout.listview_item, null); viewHolder.imageView = (ImageView) convertView.findViewById(R.id.iv_lv_item); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.imageView.setTag(url); viewHolder.imageView.setImageResource(R.drawable.ic_launcher); mImageLoader.showImage(url, viewHolder.imageView); return convertView; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (scrollState == SCROLL_STATE_IDLE) { mImageLoader.loadImages(mStart, mEnd); } else { mImageLoader.cancelAllTasks(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { mStart = firstVisibleItem; mEnd = firstVisibleItem + visibleItemCount; if (mFirstFlag && visibleItemCount > 0) { mImageLoader.loadImages(mStart, mEnd); mFirstFlag = false; } } public class ViewHolder { public ImageView imageView; } }
版权声明:本文博主原创文章。博客,未经同意不得转载。
标签:
原文地址:http://www.cnblogs.com/bhlsheji/p/4915239.html