您的位置:首页 > 移动开发 > Android开发

Android Handler 异步消息处理机制的妙用 创建强大的图片加载类

2016-11-26 13:18 633 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。

目录(?)[+]
概述
图库功能的实现
布局文件
MainActivity
GridView的适配器
ImageLoader

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38476887 ,本文出自【张鸿洋的博客】

最近创建了一个群,方便大家交流,群号:55032675

上一篇博客介绍了Android异步消息处理机制,如果你还不了解,可以看:Android
异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系 。那篇博客的最后,提出可以把异步消息处理机制不仅仅是在MainActivity中更新UI,可以用到别的地方,最近也一直在考虑这个问题,有幸,想出来一个实际的案例,将异步消息处理机制用到大量图片的加载的工具类中,其实也特别希望可以写一篇关于大量图片加载的文章,终于有机会了~先简单介绍一下:

1、概述

一般大量图片的加载,比如GridView实现手机的相册功能,一般会用到LruCache,线程池,任务队列等;那么异步消息处理可以用哪呢?

1、用于UI线程当Bitmap加载完成后更新ImageView

2、在图片加载类初始化时,我们会在一个子线程中维护一个Loop实例,当然子线程中也就有了MessageQueue,Looper会一直在那loop停着等待消息的到达,当有消息到达时,从任务队列按照队列调度的方式(FIFO,LIFO等),取出一个任务放入线程池中进行处理。

简易的一个流程:当需要加载一张图片,首先把加载图片加入任务队列,然后使用loop线程(子线程)中的hander发送一个消息,提示有任务到达,loop()(子线程)中会接着取出一个任务,去加载图片,当图片加载完成,会使用UI线程的handler发送一个消息去更新UI界面。

说了这么多,大家估计也觉得云里来雾里去的,下面看实际的例子。

2、图库功能的实现

该程序首先扫描手机中所有包含图片的文件夹,最终选择图片最多的文件夹,使用GridView显示其中的图片

1、布局文件

[html]
view plain
copy

print?





<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent" >  
  
    <GridView  
        android:id="@+id/id_gridView"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:cacheColorHint="@android:color/transparent"  
        android:columnWidth="90dip"  
        android:gravity="center"  
        android:horizontalSpacing="20dip"  
        android:listSelector="@android:color/transparent"  
        android:numColumns="auto_fit"  
        android:stretchMode="columnWidth"  
        android:verticalSpacing="20dip" >  
    </GridView>  
  
</RelativeLayout>  



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<GridView
android:id="@+id/id_gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="@android:color/transparent"
android:columnWidth="90dip"
android:gravity="center"
android:horizontalSpacing="20dip"
android:listSelector="@android:color/transparent"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="20dip" >
</GridView>

</RelativeLayout>


布局文件相当简单就一个GridView

2、MainActivity

[java]
view plain
copy

print?





package com.example.zhy_handler_imageloader;  
  
import java.io.File;  
import java.io.FilenameFilter;  
import java.util.Arrays;  
import java.util.HashSet;  
import java.util.List;  
  
import android.app.Activity;  
import android.app.ProgressDialog;  
import android.content.ContentResolver;  
import android.database.Cursor;  
import android.net.Uri;  
import android.os.Bundle;  
import android.os.Environment;  
import android.os.Handler;  
import android.provider.MediaStore;  
import android.widget.GridView;  
import android.widget.ImageView;  
import android.widget.ListAdapter;  
import android.widget.Toast;  
  
public class MainActivity extends Activity  
{  
    private ProgressDialog mProgressDialog;  
    private ImageView mImageView;  
      
    /** 
     * 存储文件夹中的图片数量 
     */  
    private int mPicsSize;  
    /** 
     * 图片数量最多的文件夹 
     */  
    private File mImgDir;  
    /** 
     * 所有的图片 
     */  
    private List<String> mImgs;  
  
    private GridView mGirdView;  
    private ListAdapter mAdapter;  
    /** 
     * 临时的辅助类,用于防止同一个文件夹的多次扫描 
     */  
    private HashSet<String> mDirPaths = new HashSet<String>();  
  
    private Handler mHandler = new Handler()  
    {  
        public void handleMessage(android.os.Message msg)  
        {  
            mProgressDialog.dismiss();  
            mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()  
            {  
                @Override  
                public boolean accept(File dir, String filename)  
                {  
                    if (filename.endsWith(".jpg"))  
                        return true;  
                    return false;  
                }  
            }));  
            /** 
             * 可以看到文件夹的路径和图片的路径分开保存,极大的减少了内存的消耗; 
             */  
            mAdapter = new MyAdapter(getApplicationContext(), mImgs,  
                    mImgDir.getAbsolutePath());  
            mGirdView.setAdapter(mAdapter);  
        };  
    };  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState)  
    {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        mGirdView = (GridView) findViewById(R.id.id_gridView);  
        getImages();  
  
    }  
  
    /** 
     * 利用ContentProvider扫描手机中的图片,此方法在运行在子线程中 完成图片的扫描,最终获得jpg最多的那个文件夹 
     */  
    private void getImages()  
    {  
        if (!Environment.getExternalStorageState().equals(  
                Environment.MEDIA_MOUNTED))  
        {  
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();  
            return;  
        }  
        // 显示进度条  
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");  
  
        new Thread(new Runnable()  
        {  
  
            @Override  
            public void run()  
            {  
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;  
                ContentResolver mContentResolver = MainActivity.this  
                        .getContentResolver();  
  
                // 只查询jpeg和png的图片  
                Cursor mCursor = mContentResolver.query(mImageUri, null,  
                        MediaStore.Images.Media.MIME_TYPE + "=? or "  
                                + MediaStore.Images.Media.MIME_TYPE + "=?",  
                        new String[] { "image/jpeg", "image/png" },  
                        MediaStore.Images.Media.DATE_MODIFIED);  
  
                while (mCursor.moveToNext())  
                {  
                    // 获取图片的路径  
                    String path = mCursor.getString(mCursor  
                            .getColumnIndex(MediaStore.Images.Media.DATA));  
                    // 获取该图片的父路径名  
                    File parentFile = new File(path).getParentFile();  
                    String dirPath = parentFile.getAbsolutePath();   
                      
                    //利用一个HashSet防止多次扫描同一个文件夹(不加这个判断,图片多起来还是相当恐怖的~~)  
                    if(mDirPaths.contains(dirPath))  
                    {  
                        continue;   
                    }  
                    else  
                    {  
                        mDirPaths.add(dirPath);  
                    }  
                      
                    int picSize = parentFile.list(new FilenameFilter()  
                    {  
                        @Override  
                        public boolean accept(File dir, String filename)  
                        {  
                            if (filename.endsWith(".jpg"))  
                                return true;  
                            return false;  
                        }  
                    }).length;  
                    if (picSize > mPicsSize)  
                    {  
                        mPicsSize = picSize;  
                        mImgDir = parentFile;  
                    }  
                }  
                mCursor.close();  
                //扫描完成,辅助的HashSet也就可以释放内存了  
                mDirPaths = null ;   
                // 通知Handler扫描图片完成  
                mHandler.sendEmptyMessage(0x110);  
  
            }  
        }).start();  
  
    }  
}  



package com.example.zhy_handler_imageloader;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.Toast;

public class MainActivity extends Activity
{
private ProgressDialog mProgressDialog;
private ImageView mImageView;

/**
* 存储文件夹中的图片数量
*/
private int mPicsSize;
/**
* 图片数量最多的文件夹
*/
private File mImgDir;
/**
* 所有的图片
*/
private List<String> mImgs;

private GridView mGirdView;
private ListAdapter mAdapter;
/**
* 临时的辅助类,用于防止同一个文件夹的多次扫描
*/
private HashSet<String> mDirPaths = new HashSet<String>();

private Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
mProgressDialog.dismiss();
mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String filename)
{
if (filename.endsWith(".jpg"))
return true;
return false;
}
}));
/**
* 可以看到文件夹的路径和图片的路径分开保存,极大的减少了内存的消耗;
*/
mAdapter = new MyAdapter(getApplicationContext(), mImgs,
mImgDir.getAbsolutePath());
mGirdView.setAdapter(mAdapter);
};
};

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGirdView = (GridView) findViewById(R.id.id_gridView);
getImages();

}

/**
* 利用ContentProvider扫描手机中的图片,此方法在运行在子线程中 完成图片的扫描,最终获得jpg最多的那个文件夹
*/
private void getImages()
{
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))
{
Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
return;
}
// 显示进度条
mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

new Thread(new Runnable()
{

@Override
public void run()
{
Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver mContentResolver = MainActivity.this
.getContentResolver();

// 只查询jpeg和png的图片
Cursor mCursor = mContentResolver.query(mImageUri, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
new String[] { "image/jpeg", "image/png" },
MediaStore.Images.Media.DATE_MODIFIED);

while (mCursor.moveToNext())
{
// 获取图片的路径
String path = mCursor.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
// 获取该图片的父路径名
File parentFile = new File(path).getParentFile();
String dirPath = parentFile.getAbsolutePath();

//利用一个HashSet防止多次扫描同一个文件夹(不加这个判断,图片多起来还是相当恐怖的~~)
if(mDirPaths.contains(dirPath))
{
continue;
}
else
{
mDirPaths.add(dirPath);
}

int picSize = parentFile.list(new FilenameFilter()
{
@Override
public boolean accept(File dir, String filename)
{
if (filename.endsWith(".jpg"))
return true;
return false;
}
}).length;
if (picSize > mPicsSize)
{
mPicsSize = picSize;
mImgDir = parentFile;
}
}
mCursor.close();
//扫描完成,辅助的HashSet也就可以释放内存了
mDirPaths = null ;
// 通知Handler扫描图片完成
mHandler.sendEmptyMessage(0x110);

}
}).start();

}
}


MainActivity也是比较简单的,使用ContentProvider辅助,找到图片最多的文件夹后,直接handler去隐藏ProgressDialog,然后初始化数据,适配器等;

但是稍微注意一下:

1、在扫描图片时,使用了一个临时的HashSet保存扫描过的文件夹,这样可以有效的避免重复扫描。比如,我手机中有个文件夹下面有3000多张图片,如果不判断则会扫描这个文件夹3000多次,处理器时间以及内存的消耗还是很可观的。

2、在适配器中,保存List<String>的时候,考虑只保存图片的名称,路径单独作为变量传入。一般情况下,图片的路径比图片名长很多,加入有3000张图片,路径长度30,图片平均长度10,则List<String>保存完成路径需要长度为:(30+10)*3000 = 120000 ; 而单独存储只需要:30+10*3000 = 30030 ; 图片越多,节省的内存越客观;

总之,尽可能的去减少内存的消耗,这些都是很容易做到的~

3、GridView的适配器

[java]
view plain
copy

print?





package com.example.zhy_handler_imageloader;  
  
import java.util.List;  
  
import android.content.Context;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.BaseAdapter;  
import android.widget.ImageView;  
  
import com.zhy.utils.ImageLoader;  
  
public class MyAdapter extends BaseAdapter  
{  
  
    private Context mContext;  
    private List<String> mData;  
    private String mDirPath;  
    private LayoutInflater mInflater;  
    private ImageLoader mImageLoader;  
  
    public MyAdapter(Context context, List<String> mData, String dirPath)  
    {  
        this.mContext = context;  
        this.mData = mData;  
        this.mDirPath = dirPath;  
        mInflater = LayoutInflater.from(mContext);  
  
        mImageLoader = ImageLoader.getInstance();  
    }  
  
    @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, final ViewGroup parent)  
    {  
        ViewHolder holder = null;  
        if (convertView == null)  
        {  
            holder = new ViewHolder();  
            convertView = mInflater.inflate(R.layout.grid_item, parent,  
                    false);  
            holder.mImageView = (ImageView) convertView  
                    .findViewById(R.id.id_item_image);  
            convertView.setTag(holder);  
        } else  
        {  
            holder = (ViewHolder) convertView.getTag();  
        }  
        holder.mImageView  
                .setImageResource(R.drawable.friends_sends_pictures_no);  
        //使用Imageloader去加载图片  
        mImageLoader.loadImage(mDirPath + "/" + mData.get(position),  
                holder.mImageView);  
        return convertView;  
    }  
  
    private final class ViewHolder  
    {  
        ImageView mImageView;  
    }  
  
}  



package com.example.zhy_handler_imageloader;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.zhy.utils.ImageLoader;

public class MyAdapter extends BaseAdapter
{

private Context mContext;
private List<String> mData;
private String mDirPath;
private LayoutInflater mInflater;
private ImageLoader mImageLoader;

public MyAdapter(Context context, List<String> mData, String dirPath)
{
this.mContext = context;
this.mData = mData;
this.mDirPath = dirPath;
mInflater = LayoutInflater.from(mContext);

mImageLoader = ImageLoader.getInstance();
}

@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, final ViewGroup parent)
{
ViewHolder holder = null;
if (convertView == null)
{
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.grid_item, parent,
false);
holder.mImageView = (ImageView) convertView
.findViewById(R.id.id_item_image);
convertView.setTag(holder);
} else
{
holder = (ViewHolder) convertView.getTag();
}
holder.mImageView
.setImageResource(R.drawable.friends_sends_pictures_no);
//使用Imageloader去加载图片
mImageLoader.loadImage(mDirPath + "/" + mData.get(position),
holder.mImageView);
return convertView;
}

private final class ViewHolder
{
ImageView mImageView;
}

}


可以看到与传统的适配器的写法基本没有什么不同之处,甚至在getView里面都没有出现常见的回调(findViewByTag~用于防止图片的错位);仅仅多了一行代码:

mImageLoader.loadImage(mDirPath + "/" + mData.get(position),holder.mImageView);是不是用起来还是相当爽的,所有需要处理的细节都被封装了。

4、ImageLoader

现在才到了关键的时刻,我们封装的ImageLoader类,当然我们的异步消息处理机制也出现在其中。

首先是一个懒加载的单例

[java]
view plain
copy

print?





/** 
     * 单例获得该实例对象 
     *  
     * @return 
     */  
    public static ImageLoader getInstance()  
    {  
  
        if (mInstance == null)  
        {  
            synchronized (ImageLoader.class)  
            {  
                if (mInstance == null)  
                {  
                    mInstance = new ImageLoader(1, Type.LIFO);  
                }  
            }  
        }  
        return mInstance;  
    }  



/**
* 单例获得该实例对象
*
* @return
*/
public static ImageLoader getInstance()
{

if (mInstance == null)
{
synchronized (ImageLoader.class)
{
if (mInstance == null)
{
mInstance = new ImageLoader(1, Type.LIFO);
}
}
}
return mInstance;
}


没啥说的,直接调用私有的构造方法,可以看到,默认传入了1(线程池中线程的数量),和LIFO(队列的工作方式)

[java]
view plain
copy

print?





private ImageLoader(int threadCount, Type type)  
    {  
        init(threadCount, type);  
    }  
  
    private void init(int threadCount, Type type)  
    {  
        // loop thread  
        mPoolThread = new Thread()  
        {  
            @Override  
            public void run()  
            {  
                try  
                {  
                    // 请求一个信号量  
                    mSemaphore.acquire();  
                } catch (InterruptedException e)  
                {  
                }  
                Looper.prepare();  
  
                mPoolThreadHander = new Handler()  
                {  
                    @Override  
                    public void handleMessage(Message msg)  
                    {  
                        mThreadPool.execute(getTask());  
                        try  
                        {  
                            mPoolSemaphore.acquire();  
                        } catch (InterruptedException e)  
                        {  
                        }  
                    }  
                };  
                // 释放一个信号量  
                mSemaphore.release();  
                Looper.loop();  
            }  
        };  
        mPoolThread.start();  
  
        // 获取应用程序最大可用内存  
        int maxMemory = (int) Runtime.getRuntime().maxMemory();  
        int cacheSize = maxMemory / 8;  
        mLruCache = new LruCache<String, Bitmap>(cacheSize)  
        {  
            @Override  
            protected int sizeOf(String key, Bitmap value)  
            {  
                return value.getRowBytes() * value.getHeight();  
            };  
        };  
  
        mThreadPool = Executors.newFixedThreadPool(threadCount);  
        mPoolSemaphore = new Semaphore(threadCount);  
        mTasks = new LinkedList<Runnable>();  
        mType = type == null ? Type.LIFO : type;  
  
    }  



private ImageLoader(int threadCount, Type type)
{
init(threadCount, type);
}

private void init(int threadCount, Type type)
{
// loop thread
mPoolThread = new Thread()
{
@Override
public void run()
{
try
{
// 请求一个信号量
mSemaphore.acquire();
} catch (InterruptedException e)
{
}
Looper.prepare();

mPoolThreadHander = new Handler()
{
@Override
public void handleMessage(Message msg)
{
mThreadPool.execute(getTask());
try
{
mPoolSemaphore.acquire();
} catch (InterruptedException e)
{
}
}
};
// 释放一个信号量
mSemaphore.release();
Looper.loop();
}
};
mPoolThread.start();

// 获取应用程序最大可用内存
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
mLruCache = new LruCache<String, Bitmap>(cacheSize)
{
@Override
protected int sizeOf(String key, Bitmap value)
{
return value.getRowBytes() * value.getHeight();
};
};

mThreadPool = Executors.newFixedThreadPool(threadCount);
mPoolSemaphore = new Semaphore(threadCount);
mTasks = new LinkedList<Runnable>();
mType = type == null ? Type.LIFO : type;

}


然后在私有构造里面调用了我们的init方法,在这个方法的开始就创建了mPoolThread这个子线程,在这个子线程中我们执行了Looper.prepare,初始化mPoolThreadHander,Looper.loop;如果看过上篇博客,一定知道,此时在这个子线程中维护了一个消息队列,且这个子线程会进入一个无限读取消息的循环中,而mPoolThreadHander这个handler发送的消息会直接发送至此线程中的消息队列。然后看mPoolThreadHander中handleMessage的方法,直接调用了getTask方法取出一个任务,然后放入线程池去执行。如果你比较细心,可能会发现里面还有一些信号量的操作的代码,如果你不了解什么是信号量,可以参考:Java
并发专题 : Semaphore 实现 互斥 与 连接池 。 简单说一下mSemaphore(信号数为1)的作用,由于mPoolThreadHander实在子线程初始化的,所以我在初始化前调用了mSemaphore.acquire去请求一个信号量,然后在初始化完成后释放了此信号量,我为什么这么做呢?因为在主线程可能会立即使用到mPoolThreadHander,但是mPoolThreadHander是在子线程初始化的,虽然速度很快,但是我也不能百分百的保证,主线程使用时已经初始化结束,为了避免空指针异常,所以我在主线程需要使用的时候,是这么调用的:

[java]
view plain
copy

print?





/** 
     * 添加一个任务 
     *  
     * @param runnable 
     */  
    private synchronized void addTask(Runnable runnable)  
    {  
        try  
        {  
            // 请求信号量,防止mPoolThreadHander为null  
            if (mPoolThreadHander == null)  
                mSemaphore.acquire();  
        } catch (InterruptedException e)  
        {  
        }  
        mTasks.add(runnable);  
        mPoolThreadHander.sendEmptyMessage(0x110);  
    }  



/**
* 添加一个任务
*
* @param runnable
*/
private synchronized void addTask(Runnable runnable)
{
try
{
// 请求信号量,防止mPoolThreadHander为null
if (mPoolThreadHander == null)
mSemaphore.acquire();
} catch (InterruptedException e)
{
}
mTasks.add(runnable);
mPoolThreadHander.sendEmptyMessage(0x110);
}


如果mPoolThreadHander没有初始化完成,则会去acquire一个信号量,其实就是去等待mPoolThreadHander初始化完成。如果对此感兴趣的,可以将关于mSemaphore的代码注释,然后在初始化mPoolThreadHander使用Thread.sleep去暂停1秒,就会发现这样的错误。

初始化结束,就会在getView中调用mImageLoader.loadImage(mDirPath + "/" + mData.get(position),holder.mImageView);方法了,所以我们去看loadImage方法吧

[java]
view plain
copy

print?





/** 
     * 加载图片 
     *  
     * @param path 
     * @param imageView 
     */  
    public void loadImage(final String path, final ImageView imageView)  
    {  
        // set tag  
        imageView.setTag(path);  
        // UI线程  
        if (mHandler == null)  
        {  
            mHandler = new Handler()  
            {  
                @Override  
                public void handleMessage(Message msg)  
                {  
                    ImgBeanHolder holder = (ImgBeanHolder) msg.obj;  
                    ImageView imageView = holder.imageView;  
                    Bitmap bm = holder.bitmap;  
                    String path = holder.path;  
                    if (imageView.getTag().toString().equals(path))  
                    {  
                        imageView.setImageBitmap(bm);  
                    }  
                }  
            };  
        }  
  
        Bitmap bm = getBitmapFromLruCache(path);  
        if (bm != null)  
        {  
            ImgBeanHolder holder = new ImgBeanHolder();  
            holder.bitmap = bm;  
            holder.imageView = imageView;  
            holder.path = path;  
            Message message = Message.obtain();  
            message.obj = holder;  
            mHandler.sendMessage(message);  
        } else  
        {  
            addTask(new Runnable()  
            {  
                @Override  
                public void run()  
                {  
  
                    ImageSize imageSize = getImageViewWidth(imageView);  
  
                    int reqWidth = imageSize.width;  
                    int reqHeight = imageSize.height;  
  
                    Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth,  
                            reqHeight);  
                    addBitmapToLruCache(path, bm);  
                    ImgBeanHolder holder = new ImgBeanHolder();  
                    holder.bitmap = getBitmapFromLruCache(path);  
                    holder.imageView = imageView;  
                    holder.path = path;  
                    Message message = Message.obtain();  
                    message.obj = holder;  
                    // Log.e("TAG", "mHandler.sendMessage(message);");  
                    mHandler.sendMessage(message);  
                    mPoolSemaphore.release();  
                }  
            });  
        }  
  
    }  



/**
* 加载图片
*
* @param path
* @param imageView
*/
public void loadImage(final String path, final ImageView imageView)
{
// set tag
imageView.setTag(path);
// UI线程
if (mHandler == null)
{
mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
ImgBeanHolder holder = (ImgBeanHolder) msg.obj;
ImageView imageView = holder.imageView;
Bitmap bm = holder.bitmap;
String path = holder.path;
if (imageView.getTag().toString().equals(path))
{
imageView.setImageBitmap(bm);
}
}
};
}

Bitmap bm = getBitmapFromLruCache(path);
if (bm != null)
{
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = bm;
holder.imageView = imageView;
holder.path = path;
Message message = Message.obtain();
message.obj = holder;
mHandler.sendMessage(message);
} else
{
addTask(new Runnable()
{
@Override
public void run()
{

ImageSize imageSize = getImageViewWidth(imageView);

int reqWidth = imageSize.width;
int reqHeight = imageSize.height;

Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth,
reqHeight);
addBitmapToLruCache(path, bm);
ImgBeanHolder holder = new ImgBeanHolder();
holder.bitmap = getBitmapFromLruCache(path);
holder.imageView = imageView;
holder.path = path;
Message message = Message.obtain();
message.obj = holder;
// Log.e("TAG", "mHandler.sendMessage(message);");
mHandler.sendMessage(message);
mPoolSemaphore.release();
}
});
}

}


这段代码比较长,当然也是比较核心的代码了

10-29行:首先将传入imageView设置了path,然在初始化了一个mHandler用于设置imageView的bitmap,注意此时在UI线程,也就是这个mHandler发出的消息,会在UI线程中调用。可以看到在handleMessage中,我们从消息中取出ImageView,bitmap,path;然后将path与imageView的tag进行比较,防止图片的错位,最后设置bitmap;

31行:我们首先去从LruCache中去查找是否已经缓存了此图片

32-40:如果找到了,则直接使用mHandler去发送消息,这里使用了一个ImgBeanHolder去封装了ImageView,Bitmap,Path这三个对象。然后更新执行handleMessage代码去更新UI

43-66行:如果没有存在缓存中,则创建一个Runnable对象作为任务,去执行addTask方法加入任务队列

49行:getImageViewWidth根据ImageView获取适当的图片的尺寸,用于后面的压缩图片,代码按顺序贴下下面

54行:会根据计算的需要的宽和高,对图片进行压缩。代码按顺序贴下下面

56行:将压缩后的图片放入缓存

58-64行,创建消息,使用mHandler进行发送,更新UI

[java]
view plain
copy

print?





/** 
     * 根据ImageView获得适当的压缩的宽和高 
     *  
     * @param imageView 
     * @return 
     */  
    private ImageSize getImageViewWidth(ImageView imageView)  
    {  
        ImageSize imageSize = new ImageSize();  
        final DisplayMetrics displayMetrics = imageView.getContext()  
                .getResources().getDisplayMetrics();  
        final LayoutParams params = imageView.getLayoutParams();  
  
        int width = params.width == LayoutParams.WRAP_CONTENT ? 0 : imageView  
                .getWidth(); // Get actual image width  
        if (width <= 0)  
            width = params.width; // Get layout width parameter  
        if (width <= 0)  
            width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check  
                                                                    // maxWidth  
                                                                    // parameter  
        if (width <= 0)  
            width = displayMetrics.widthPixels;  
        int height = params.height == LayoutParams.WRAP_CONTENT ? 0 : imageView  
                .getHeight(); // Get actual image height  
        if (height <= 0)  
            height = params.height; // Get layout height parameter  
        if (height <= 0)  
            height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check  
                                                                        // maxHeight  
                                                                        // parameter  
        if (height <= 0)  
            height = displayMetrics.heightPixels;  
        imageSize.width = width;  
        imageSize.height = height;  
        return imageSize;  
  
    }  



/**
* 根据ImageView获得适当的压缩的宽和高
*
* @param imageView
* @return
*/
private ImageSize getImageViewWidth(ImageView imageView)
{
ImageSize imageSize = new ImageSize();
final DisplayMetrics displayMetrics = imageView.getContext()
.getResources().getDisplayMetrics();
final LayoutParams params = imageView.getLayoutParams();

int width = params.width == LayoutParams.WRAP_CONTENT ? 0 : imageView
.getWidth(); // Get actual image width
if (width <= 0)
width = params.width; // Get layout width parameter
if (width <= 0)
width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check
// maxWidth
// parameter
if (width <= 0)
width = displayMetrics.widthPixels;
int height = params.height == LayoutParams.WRAP_CONTENT ? 0 : imageView
.getHeight(); // Get actual image height
if (height <= 0)
height = params.height; // Get layout height parameter
if (height <= 0)
height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check
// maxHeight
// parameter
if (height <= 0)
height = displayMetrics.heightPixels;
imageSize.width = width;
imageSize.height = height;
return imageSize;

}


[java]
view plain
copy

print?





/** 
     * 根据计算的inSampleSize,得到压缩后图片 
     *  
     * @param pathName 
     * @param reqWidth 
     * @param reqHeight 
     * @return 
     */  
    private Bitmap decodeSampledBitmapFromResource(String pathName,  
            int reqWidth, int reqHeight)  
    {  
        // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小  
        final BitmapFactory.Options options = new BitmapFactory.Options();  
        options.inJustDecodeBounds = true;  
        BitmapFactory.decodeFile(pathName, options);  
        // 调用上面定义的方法计算inSampleSize值  
        options.inSampleSize = calculateInSampleSize(options, reqWidth,  
                reqHeight);  
        // 使用获取到的inSampleSize值再次解析图片  
        options.inJustDecodeBounds = false;  
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);  
  
        return bitmap;  
    }  



/**
* 根据计算的inSampleSize,得到压缩后图片
*
* @param pathName
* @param reqWidth
* @param reqHeight
* @return
*/
private Bitmap decodeSampledBitmapFromResource(String pathName,
int reqWidth, int reqHeight)
{
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);

return bitmap;
}
接下来看AddTask的代码:

[java]
view plain
copy

print?





/** 
     * 添加一个任务 
     *  
     * @param runnable 
     */  
    private synchronized void addTask(Runnable runnable)  
    {  
        try  
        {  
            // 请求信号量,防止mPoolThreadHander为null  
            if (mPoolThreadHander == null)  
                mSemaphore.acquire();  
        } catch (InterruptedException e)  
        {  
        }  
        mTasks.add(runnable);  
        mPoolThreadHander.sendEmptyMessage(0x110);  
    }  



/**
* 添加一个任务
*
* @param runnable
*/
private synchronized void addTask(Runnable runnable)
{
try
{
// 请求信号量,防止mPoolThreadHander为null
if (mPoolThreadHander == null)
mSemaphore.acquire();
} catch (InterruptedException e)
{
}
mTasks.add(runnable);
mPoolThreadHander.sendEmptyMessage(0x110);
}


可以看到,简单把任务放入任务队列,然后使用mPoolThreadHander发送一个消息到后台的loop中,后台的loop会取出消息执行:mThreadPool.execute(getTask());

execute执行的就是上面分析的Runnable中的run方法了。

注意一下:上述代码中还会看到mPoolSemaphore这个信号量的身影,说下用处;因为调用addTask之后,会直接去从任务队列取出一个任务,放入线程池,由于线程池内部其实也维持着一个队列,那么”从任务队列取出一个任务”这个动作会瞬间完成,直接加入线程池维护的队列中;这样会造成比如用户设置了调度队列为LIFO,但是由于”从任务队列取出一个任务”这个动作会瞬间完成,队列中始终维持在空队列的状态,所以让用户感觉LIFO根本没有效果;所以我按照用户设置线程池工作线程的数量设置了一个信号量,这样在保证任务执行完后,才会从任务队列去取任务,使得LIFO有着很好的效果;有兴趣的可以注释了所有的mPoolSemaphore代码,测试下就明白了。

到此代码基本介绍完毕。细节还是很多的,后面会附上源码,有兴趣的研究下代码,没有兴趣的,可以运行下代码,如果感觉流畅性不错,体验不错,可以作为工具类直接使用,使用也就getView里面一行代码。

贴一下效果图,我手机最多的文件夹大概3000张图片,加载速度还是相当相当流畅的:



真机录的,有点丢帧,注意看效果图,中间我疯狂拖动滚动条,但是图片基本还是瞬间显示的。

说一下,FIFO如果设置为这个模式,在控件中不做处理的话,用户拉的比较慢效果还是不错的,但是用户手机如果有个几千张,瞬间拉到最后,最后一屏图片的显示可能需要喝杯茶了~当然了,大家可以在控件中做处理,要么,拖动的时候不去加载图片,停在来再加载。或者,当手机抬起,给了一个很大的加速度,屏幕还是很快的滑动时停止加载,停下时加载图片。

LIFO这个模式可能用户体验会好很多,不管用户拉多块,最终停下来的那一屏图片都会瞬间显示~

最后掰一掰使用异步消息处理机制作为背后的子线程的好处,其实直接用一个子线程也可以实现,但是,这个子线程run中可能需要while(true)然后每隔200毫秒甚至更短的时间去查询任务队列是否有任务,没有则Thread.sleep,然后再去查询;这样如果长时间没有去添加任务,这个线程依然会不断的去查询;

而异步消息机制,只有在发送消息时才会去执行,当然更准确;当长时间没有任务到达时,也不会去查询,会一直阻塞在这;还有一点,这个机制Android内部实现的,怎么也比我们搞个Thread稳定性、效率高吧~

源码点击下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐