«

Listview异步加载图片之优化篇(有图有码有解释)

时间:2024-3-2 18:53     作者:韩俊     分类: Android


分类: Android平台

在APP应用中,listview的异步加载图片方式能够带来很好的用户体验,同时也是考量程序性能的一个重要指标。关于listview的异步加载,网上其实很多示例了,中心思想都差不多,不过很多版本或是有bug,或是有性能问题有待优化。有鉴于此,本人在网上找了个相对理想的版本并在此基础上进行改造,下面就让在下阐述其原理以探索个中奥秘,与诸君共赏…


贴张效果图先:


异步加载图片基本思想:

1. 先从内存缓存中获取图片显示(内存缓冲)

2. 获取不到的话从SD卡里获取(SD卡缓冲)

3. 都获取不到的话从网络下载图片并保存到SD卡同时加入内存并显示(视情况看是否要显示)


OK,先上adapter的代码:


点击(此处)折叠或打开

public class LoaderAdapter extends BaseAdapter{


    private static final String TAG = &quot;LoaderAdapter&quot;;<br style="word-wrap:break-word">

    private boolean mBusy = false;<br style="word-wrap:break-word">


    public void setFlagBusy(boolean busy) {<br style="word-wrap:break-word">

            this.mBusy = busy;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


     <br style="word-wrap:break-word">

    private ImageLoader mImageLoader;<br style="word-wrap:break-word">

    private int mCount;<br style="word-wrap:break-word">

    private Context mContext;<br style="word-wrap:break-word">

    private String[] urlArrays;<br style="word-wrap:break-word">

     <br style="word-wrap:break-word">

     <br style="word-wrap:break-word">

    public LoaderAdapter(int count, Context context, String []url) {<br style="word-wrap:break-word">

            this.mCount = count;<br style="word-wrap:break-word">

            this.mContext = context;<br style="word-wrap:break-word">

            urlArrays = url;<br style="word-wrap:break-word">

            mImageLoader = new ImageLoader(context);<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">

     <br style="word-wrap:break-word">

    public ImageLoader getImageLoader(){<br style="word-wrap:break-word">

            return mImageLoader;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    @Override<br style="word-wrap:break-word">

    public int getCount() {<br style="word-wrap:break-word">

            return mCount;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    @Override<br style="word-wrap:break-word">

    public Object getItem(int position) {<br style="word-wrap:break-word">

            return position;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    @Override<br style="word-wrap:break-word">

    public long getItemId(int position) {<br style="word-wrap:break-word">

            return position;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    @Override<br style="word-wrap:break-word">

    public View getView(int position, View convertView, ViewGroup parent) {<br style="word-wrap:break-word">


            ViewHolder viewHolder = null;<br style="word-wrap:break-word">

            if (convertView == null) {<br style="word-wrap:break-word">

                    convertView = LayoutInflater.from(mContext).inflate(<br style="word-wrap:break-word">

                                    R.layout.list_item, null);<br style="word-wrap:break-word">

                    viewHolder = new ViewHolder();<br style="word-wrap:break-word">

                    viewHolder.mTextView = (TextView) convertView<br style="word-wrap:break-word">

                                    .findViewById(R.id.tv_tips);<br style="word-wrap:break-word">

                    viewHolder.mImageView = (ImageView) convertView<br style="word-wrap:break-word">

                                    .findViewById(R.id.iv_image);<br style="word-wrap:break-word">

                    convertView.setTag(viewHolder);<br style="word-wrap:break-word">

            } else {<br style="word-wrap:break-word">

                    viewHolder = (ViewHolder) convertView.getTag();<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

            String url = &quot;&quot;;<br style="word-wrap:break-word">

            url = urlArrays[position % urlArrays.length];<br style="word-wrap:break-word">

             <br style="word-wrap:break-word">

            viewHolder.mImageView.setImageResource(R.drawable.ic_launcher);<br style="word-wrap:break-word">

             <br style="word-wrap:break-word">


            if (!mBusy) {<br style="word-wrap:break-word">

                    mImageLoader.DisplayImage(url, viewHolder.mImageView, false);<br style="word-wrap:break-word">

                    viewHolder.mTextView.setText(&quot;--&quot; &#43; position<br style="word-wrap:break-word">

                                    &#43; &quot;--IDLE ||TOUCH_SCROLL&quot;);<br style="word-wrap:break-word">

            } else {<br style="word-wrap:break-word">

                    mImageLoader.DisplayImage(url, viewHolder.mImageView, true); 
           <br style="word-wrap:break-word">

                    viewHolder.mTextView.setText(&quot;--&quot; &#43; position &#43; &quot;--FLING&quot;);<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

            return convertView;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    static class ViewHolder {<br style="word-wrap:break-word">

            TextView mTextView;<br style="word-wrap:break-word">

            ImageView mImageView;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">

}

关键代码是ImageLoader的DisplayImage方法,再看ImageLoader的实现


点击(此处)折叠或打开

public class ImageLoader {


    private MemoryCache memoryCache = new MemoryCache();<br style="word-wrap:break-word">

    private AbstractFileCache fileCache;<br style="word-wrap:break-word">

    private Map&lt;ImageView, String&gt; imageViews = Collections<br style="word-wrap:break-word">

                    .synchronizedMap(new WeakHashMap&lt;ImageView, String&gt;());<br style="word-wrap:break-word">

    // 线程池<br style="word-wrap:break-word">

    private ExecutorService executorService;<br style="word-wrap:break-word">


    public ImageLoader(Context context) {<br style="word-wrap:break-word">

            fileCache = new FileCache(context);<br style="word-wrap:break-word">

            executorService = Executors.newFixedThreadPool(5);<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    // 最主要的方法<br style="word-wrap:break-word">

    public void DisplayImage(String url, ImageView imageView, boolean isLoadOnlyFromCache) {<br style="word-wrap:break-word">

            imageViews.put(imageView, url);<br style="word-wrap:break-word">

            // 先从内存缓存中查找<br style="word-wrap:break-word">


            Bitmap bitmap = memoryCache.get(url);<br style="word-wrap:break-word">

            if (bitmap != null)<br style="word-wrap:break-word">

                    imageView.setImageBitmap(bitmap);<br style="word-wrap:break-word">

            else if (!isLoadOnlyFromCache){<br style="word-wrap:break-word">

                     <br style="word-wrap:break-word">

                    // 若没有的话则开启新线程加载图片<br style="word-wrap:break-word">

                    queuePhoto(url, imageView);<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    private void queuePhoto(String url, ImageView imageView) {<br style="word-wrap:break-word">

            PhotoToLoad p = new PhotoToLoad(url, imageView);<br style="word-wrap:break-word">

            executorService.submit(new PhotosLoader(p));<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    private Bitmap getBitmap(String url) {<br style="word-wrap:break-word">

            File f = fileCache.getFile(url);<br style="word-wrap:break-word">

             <br style="word-wrap:break-word">

            // 先从文件缓存中查找是否有<br style="word-wrap:break-word">

            Bitmap b = null;<br style="word-wrap:break-word">

            if (f != null &amp;&amp; f.exists()){<br style="word-wrap:break-word">

                    b = decodeFile(f);<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

            if (b != null){<br style="word-wrap:break-word">

                    return b;<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

            // 最后从指定的url中下载图片<br style="word-wrap:break-word">

            try {<br style="word-wrap:break-word">

                    Bitmap bitmap = null;<br style="word-wrap:break-word">

                    URL imageUrl = new URL(url);<br style="word-wrap:break-word">

                    HttpURLConnection conn = (HttpURLConnection) imageUrl<br style="word-wrap:break-word">

                                    .openConnection();<br style="word-wrap:break-word">

                    conn.setConnectTimeout(30000);<br style="word-wrap:break-word">

                    conn.setReadTimeout(30000);<br style="word-wrap:break-word">

                    conn.setInstanceFollowRedirects(true);<br style="word-wrap:break-word">

                    InputStream is = conn.getInputStream();<br style="word-wrap:break-word">

                    OutputStream os = new FileOutputStream(f);<br style="word-wrap:break-word">

                    CopyStream(is, os);<br style="word-wrap:break-word">

                    os.close();<br style="word-wrap:break-word">

                    bitmap = decodeFile(f);<br style="word-wrap:break-word">

                    return bitmap;<br style="word-wrap:break-word">

            } catch (Exception ex) {<br style="word-wrap:break-word">

                    Log.e(&quot;&quot;, &quot;getBitmap

catch Exception...nmessage = " + ex.getMessage());

                    return null;<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    // decode这个图片并且按比例缩放以减少内存消耗,虚拟机对每张图片的缓存大小也是有限制的<br style="word-wrap:break-word">

    private Bitmap decodeFile(File f) {<br style="word-wrap:break-word">

            try {<br style="word-wrap:break-word">

                    // decode image size<br style="word-wrap:break-word">

                    BitmapFactory.Options o = new BitmapFactory.Options();<br style="word-wrap:break-word">

                    o.inJustDecodeBounds = true;<br style="word-wrap:break-word">

                    BitmapFactory.decodeStream(new FileInputStream(f), null, o);<br style="word-wrap:break-word">


                    // Find the correct scale value. It should be the power of 2.<br style="word-wrap:break-word">

                    final int REQUIRED_SIZE = 100;<br style="word-wrap:break-word">

                    int width_tmp = o.outWidth, height_tmp = o.outHeight;<br style="word-wrap:break-word">

                    int scale = 1;<br style="word-wrap:break-word">

                    while (true) {<br style="word-wrap:break-word">

                            if (width_tmp / 2 &lt; REQUIRED_SIZE<br style="word-wrap:break-word">

                                            || height_tmp / 2 &lt; REQUIRED_SIZE)<br style="word-wrap:break-word">

                                    break;<br style="word-wrap:break-word">

                            width_tmp /= 2;<br style="word-wrap:break-word">

                            height_tmp /= 2;<br style="word-wrap:break-word">

                            scale *= 2;<br style="word-wrap:break-word">

                    }<br style="word-wrap:break-word">


                    // decode with inSampleSize<br style="word-wrap:break-word">

                    BitmapFactory.Options o2 = new BitmapFactory.Options();<br style="word-wrap:break-word">

                    o2.inSampleSize = scale;<br style="word-wrap:break-word">

                    return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);<br style="word-wrap:break-word">

            } catch (FileNotFoundException e) {<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

            return null;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    // Task for the queue<br style="word-wrap:break-word">

    private class PhotoToLoad {<br style="word-wrap:break-word">

            public String url;<br style="word-wrap:break-word">

            public ImageView imageView;<br style="word-wrap:break-word">


            public PhotoToLoad(String u, ImageView i) {<br style="word-wrap:break-word">

                    url = u;<br style="word-wrap:break-word">

                    imageView = i;<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    class PhotosLoader implements Runnable {<br style="word-wrap:break-word">

            PhotoToLoad photoToLoad;<br style="word-wrap:break-word">


            PhotosLoader(PhotoToLoad photoToLoad) {<br style="word-wrap:break-word">

                    this.photoToLoad = photoToLoad;<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">


            @Override<br style="word-wrap:break-word">

            public void run() {<br style="word-wrap:break-word">

                    if (imageViewReused(photoToLoad))<br style="word-wrap:break-word">

                            return;<br style="word-wrap:break-word">

                    Bitmap bmp = getBitmap(photoToLoad.url);<br style="word-wrap:break-word">

                    memoryCache.put(photoToLoad.url, bmp);<br style="word-wrap:break-word">

                    if (imageViewReused(photoToLoad))<br style="word-wrap:break-word">

                            return;<br style="word-wrap:break-word">

                    BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);<br style="word-wrap:break-word">

                    // 更新的操作放在UI线程中<br style="word-wrap:break-word">

                    Activity a = (Activity) photoToLoad.imageView.getContext();<br style="word-wrap:break-word">

                    a.runOnUiThread(bd);<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    /**<br style="word-wrap:break-word">

     * 防止图片错位<br style="word-wrap:break-word">

     * <br style="word-wrap:break-word">

     * @param photoToLoad<br style="word-wrap:break-word">

     * @return<br style="word-wrap:break-word">

     */<br style="word-wrap:break-word">

    boolean imageViewReused(PhotoToLoad photoToLoad) {<br style="word-wrap:break-word">

            String tag = imageViews.get(photoToLoad.imageView);<br style="word-wrap:break-word">

            if (tag == null || !tag.equals(photoToLoad.url))<br style="word-wrap:break-word">

                    return true;<br style="word-wrap:break-word">

            return false;<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    // 用于在UI线程中更新界面<br style="word-wrap:break-word">

    class BitmapDisplayer implements Runnable {<br style="word-wrap:break-word">

            Bitmap bitmap;<br style="word-wrap:break-word">

            PhotoToLoad photoToLoad;<br style="word-wrap:break-word">


            public BitmapDisplayer(Bitmap b, PhotoToLoad p) {<br style="word-wrap:break-word">

                    bitmap = b;<br style="word-wrap:break-word">

                    photoToLoad = p;<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">


            public void run() {<br style="word-wrap:break-word">

                    if (imageViewReused(photoToLoad))<br style="word-wrap:break-word">

                            return;<br style="word-wrap:break-word">

                    if (bitmap != null)<br style="word-wrap:break-word">

                            photoToLoad.imageView.setImageBitmap(bitmap);<br style="word-wrap:break-word">

     <br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    public void clearCache() {<br style="word-wrap:break-word">

            memoryCache.clear();<br style="word-wrap:break-word">

            fileCache.clear();<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    public static void CopyStream(InputStream is, OutputStream os) {<br style="word-wrap:break-word">

            final int buffer_size = 1024;<br style="word-wrap:break-word">

            try {<br style="word-wrap:break-word">

                    byte[] bytes = new byte[buffer_size];<br style="word-wrap:break-word">

                    for (;;) {<br style="word-wrap:break-word">

                            int count = is.read(bytes, 0, buffer_size);<br style="word-wrap:break-word">

                            if (count == -1)<br style="word-wrap:break-word">

                                    break;<br style="word-wrap:break-word">

                            os.write(bytes, 0, count);<br style="word-wrap:break-word">

                    }<br style="word-wrap:break-word">

            } catch (Exception ex) {<br style="word-wrap:break-word">

                    Log.e(&quot;&quot;, &quot;CopyStream

catch Exception...");

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">

}

先从内存中加载,没有则开启线程从SD卡或网络中获取,这里注意从SD卡获取图片是放在子线程里执行的,否则快速滑屏的话会不够流畅,这是优化一。于此同时,在adapter里有个busy变量,表示listview是否处于滑动状态,如果是滑动状态则仅从内存中获取图片,没有的话无需再开启线程去外存或网络获取图片,这是优化二。ImageLoader里的线程使用了线程池,从而避免了过多线程频繁创建和销毁,有的童鞋每次总是new一个线程去执行这是非常不可取的,好一点的用的AsyncTask类,其实内部也是用到了线程池。在从网络获取图片时,先是将其保存到sd卡,然后再加载到内存,这么做的好处是在加载到内存时可以做个压缩处理,以减少图片所占内存,这是优化三。


而图片错位问题的本质源于我们的listview使用了缓存convertView,假设一种场景,一个listview一屏显示九个item,那么在拉出第十个item的时候,事实上该item是重复使用了第一个item,也就是说在第一个item从网络中下载图片并最终要显示的时候其实该item已经不在当前显示区域内了,此时显示的后果将是在可能在第十个item上输出图像,这就导致了图片错位的问题。所以解决之道在于可见则显示,不可见则不显示。在ImageLoader里有个imageViews的map对象,就是用于保存当前显示区域图像对应的url集,在显示前判断处理一下即可。

下面再说下内存缓冲机制,本例采用的是LRU算法,先看看MemoryCache的实现


点击(此处)折叠或打开

public class MemoryCache {


    private static final String TAG = &quot;MemoryCache&quot;;<br style="word-wrap:break-word">

    // 放入缓存时是个同步操作<br style="word-wrap:break-word">

    // LinkedHashMap构造方法的最后一个参数true代表这个map里的元素将按照最近使用次数由少到多排列,即LRU<br style="word-wrap:break-word">

    // 这样的好处是如果要将缓存中的元素替换,则先遍历出最近最少使用的元素来替换以提高效率<br style="word-wrap:break-word">

    private Map&lt;String, Bitmap&gt; cache = Collections<br style="word-wrap:break-word">

                    .synchronizedMap(new LinkedHashMap&lt;String, Bitmap&gt;(10, 1.5f, true));<br style="word-wrap:break-word">

    // 缓存中图片所占用的字节,初始0,将通过此变量严&#26684;控制缓存所占用的堆内存<br style="word-wrap:break-word">

    private long size = 0;//

current allocated size

    // 缓存只能占用的最大堆内存<br style="word-wrap:break-word">

    private long limit = 1000000;//

max memory in bytes


    public MemoryCache() {<br style="word-wrap:break-word">

            // use 25% of available heap size<br style="word-wrap:break-word">

            setLimit(Runtime.getRuntime().maxMemory() / 10);<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    public void setLimit(long new_limit) {<br style="word-wrap:break-word">

            limit = new_limit;<br style="word-wrap:break-word">

            Log.i(TAG, &quot;MemoryCache

will use up to " + limit / 1024. / 1024. + "MB");

    }<br style="word-wrap:break-word">


    public Bitmap get(String id) {<br style="word-wrap:break-word">

            try {<br style="word-wrap:break-word">

                    if (!cache.containsKey(id))<br style="word-wrap:break-word">

                            return null;<br style="word-wrap:break-word">

                    return cache.get(id);<br style="word-wrap:break-word">

            } catch (NullPointerException ex) {<br style="word-wrap:break-word">

                    return null;<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    public void put(String id, Bitmap

bitmap) {

            try {<br style="word-wrap:break-word">

                    if (cache.containsKey(id))<br style="word-wrap:break-word">

                            size -= getSizeInBytes(cache.get(id));<br style="word-wrap:break-word">

                    cache.put(id, bitmap);<br style="word-wrap:break-word">

                    size &#43;= getSizeInBytes(bitmap);<br style="word-wrap:break-word">

                    checkSize();<br style="word-wrap:break-word">

            } catch (Throwable th) {<br style="word-wrap:break-word">

                    th.printStackTrace();<br style="word-wrap:break-word">

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    /**<br style="word-wrap:break-word">

     * 严&#26684;控制堆内存,如果超过将首先替换最近最少使用的那个图片缓存<br style="word-wrap:break-word">

     * <br style="word-wrap:break-word">

     */<br style="word-wrap:break-word">

    private void checkSize() {<br style="word-wrap:break-word">

            Log.i(TAG, &quot;cache

size=" + size + "
length=" + cache.size());

            if (size &gt; limit) {<br style="word-wrap:break-word">

                    // 先遍历最近最少使用的元素<br style="word-wrap:break-word">

                    Iterator&lt;Entry&lt;String, Bitmap&gt;&gt; iter = cache.entrySet().iterator();<br style="word-wrap:break-word">

                    while (iter.hasNext()) {<br style="word-wrap:break-word">

                            Entry&lt;String, Bitmap&gt; entry = iter.next();<br style="word-wrap:break-word">

                            size -= getSizeInBytes(entry.getValue());<br style="word-wrap:break-word">

                            iter.remove();<br style="word-wrap:break-word">

                            if (size &lt;= limit)<br style="word-wrap:break-word">

                                    break;<br style="word-wrap:break-word">

                    }<br style="word-wrap:break-word">

                    Log.i(TAG, &quot;Clean

cache. New size " + cache.size());

            }<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    public void clear() {<br style="word-wrap:break-word">

            cache.clear();<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">


    /**<br style="word-wrap:break-word">

     * 图片占用的内存<br style="word-wrap:break-word">

     * <br style="word-wrap:break-word">

     * &lt;a href=&quot;&quot;http://www.eoeandroid.com/home.php?mod=space&amp;uid=2768922&quot;&quot; target=&quot;&quot;_blank&quot;&quot;&gt;@Param&lt;/a&gt; bitmap<br style="word-wrap:break-word">

     * <br style="word-wrap:break-word">

     * @return<br style="word-wrap:break-word">

     */<br style="word-wrap:break-word">

    long getSizeInBytes(Bitmap bitmap) {<br style="word-wrap:break-word">

            if (bitmap == null)<br style="word-wrap:break-word">

                    return 0;<br style="word-wrap:break-word">

            return bitmap.getRowBytes() * bitmap.getHeight();<br style="word-wrap:break-word">

    }<br style="word-wrap:break-word">

}

首先限制内存图片缓冲的堆内存大小,每次有图片往缓存里加时判断是否超过限制大小,超过的话就从中取出最少使用的图片并将其移除,当然这里如果不采用这种方式,换做软引用也是可行的,二者目的皆是最大程度的利用已存在于内存中的图片缓存,避免重复制造垃圾增加GC负担,OOM溢出往往皆因内存瞬时大量增加而垃圾回收不及时造成的。只不过二者区别在于LinkedHashMap里的图片缓存在没有移除出去之前是不会被GC回收的,而SoftReference里的图片缓存在没有其他引用保存时随时都会被GC回收。所以在使用LinkedHashMap这种LRU算法缓存更有利于图片的有效命中,当然二者配合使用的话效果更佳,即从LinkedHashMap里移除出的缓存放到SoftReference里,这就是内存的二级缓存,有兴趣的童鞋不凡一试。


下面附上工程链接:



亦可上github下载

github下载地址:https://github.com/geniusgithub/SyncLoaderBitmapDemo

标签: android

热门推荐