最近做的项目中,都是需要从网络加载大量图片,如果在每个activity中处理,代码重用率不高,而且很容易报oom,所以我参考了郭神的博客,写了个加载类,也算是一个小框架,用起来挺方便的。
首先我们来说一下要求,不能报oom是必须的,而且加载起来要快,所以这里我们用Android自带的的LruCache来进行图片的缓存管理,而当我退出应用再打开后,上一次加载的图片也不应该再次去网上请求,所以我们需要把它保存到手机sd卡里,这里用DiskLruCache来实现硬盘缓存,主要的方向大致是这样,现在我们来实现。
首先我们需要引入DiskLruCache源文件,新建一个libcore.io包,把DiskLruCache.java拉进去。
然后我们来实现今天的主角LoadBitmap:
初始化我们采用单例模式,避免创建多个缓存空间:
public static LoadBitmap getInstance(Context context, ViewGroup viewGroup) {
if (mInstance == null) {
synchronized (LoadBitmap.class) {
if (mInstance == null) {
mInstance = new LoadBitmap(context, viewGroup);
}
}
}
return mInstance;
}
在构造函数中初始化LruCache和DiskLruCache:
public LoadBitmap(Context context, ViewGroup viewGroup) {
this.viewGroup = viewGroup;
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount();
}
};
try {
// 获取图片缓存路径
File cacheDir = getDiskCacheDir(context, "thumb");
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
// 创建DiskLruCache实例,初始化缓存数据
mDiskLruCache = DiskLruCache.open(cacheDir, getAppVersion(context),
1, 50 * 1024 * 1024);
} catch (IOException e) {
e.printStackTrace();
}
}
在这里,我们获取应用所能拥有的最大内存,然后划出1/8来作为图片缓存区,而DiskLruCache则只需要调用open函数,第一个参数指定的是数据的缓存地址,第二个参数指定当前应用程序的版本号,第三个参数指定同一个key可以对应多少个缓存文件,基本都是传1,第四个参数指定最多可以缓存多少字节的数据,就可以获得实例。
在初始化完成后,就可以调用loadBitmaps(ImageView imageView, String imageUrl, int reques_width)进行图片加载:
/**
* 加载Bitmap对象。此方法会在LruCache中检查所有屏幕中可见的ImageView的Bitmap对象,
* 如果发现任何一个ImageView的Bitmap对象不在缓存中,就会开启异步线程去下载图片。
*/
public void loadBitmaps(ImageView imageView, String imageUrl,
int reques_width) {
try {
Bitmap bitmap = getBitmapFromMemoryCache(imageUrl);
if (bitmap == null) {
BitmapWorkerTask task = new BitmapWorkerTask();
String[] parms = new String[2];
parms[0] = imageUrl;
parms[1] = reques_width+"";
task.execute(parms);
} else {
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
这里的参数分别为加载完成后显示的ImageView,图片的连接,和所期望的分辨率(用于压缩图片),在方法中,首先会在LruCache中检查是否存在需要的bitmap,如果不存在,就开始异步任务去下载,若存在就直接显示。
然后我们来看看BitmapWorkerTask 这个类:
/**
* 异步下载图片的任务。
*
*
*/
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
/**
* 图片的URL地址
*/
private String imageUrl;
@Override
protected Bitmap doInBackground(String... params) {
imageUrl = params[0];
FileDescriptor fileDescriptor = null;
FileInputStream fileInputStream = null;
Snapshot snapShot = null;
try {
// 生成图片URL对应的key
final String key = hashKeyForDisk(imageUrl);
// 查找key对应的缓存
snapShot = mDiskLruCache.get(key);
if (snapShot == null) {
// 如果没有找到对应的缓存,则准备从网络上请求数据,并写入缓存
DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if (editor != null) {
OutputStream outputStream = editor.newOutputStream(0);
if (downloadUrlToStream(imageUrl, outputStream)) {
editor.commit();
} else {
editor.abort();
}
}
// 缓存被写入后,再次查找key对应的缓存
snapShot = mDiskLruCache.get(key);
}
if (snapShot != null) {
fileInputStream = (FileInputStream) snapShot
.getInputStream(0);
fileDescriptor = fileInputStream.getFD();
}
// 将缓存数据解析成Bitmap对象
Bitmap bitmap = null;
if (fileDescriptor != null) {
// 压缩图片
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor,
new Rect(), options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = calculateInSampleSize(options,
Integer.parseInt(params[1]), 100);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor,
new Rect(), options);
}
if (bitmap != null) {
// 将Bitmap对象添加到内存缓存当中
addBitmapToMemoryCache(params[0], bitmap);
} else {
}
return bitmap;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileDescriptor == null && fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
}
}
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
// 根据Tag找到相应的ImageView控件,将下载好的图片显示出来。
ImageView imageView = (ImageView) viewGroup
.findViewWithTag(imageUrl);
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
}
}
首先我们根据图片连接来生成硬盘缓存的key,然后通过mDiskLruCache.get(key)来查找是否存在图片,不存在,则调用downloadUrlToStream去网络加载图片,完成后再次获取snapShot,若是已经存在,就直接通过snapShot来得到fileDescriptor,以此来获取bitmap。在获取bitmap对象前,我们首先需要计算下是否需要压缩,options.inSampleSize = calculateInSampleSize(options, Integer.parseInt(params[1]), 100);,计算后再去获取bitmap对象并把它加到LruCache中,返回结束到onPostExecute方法。在onPostExecute中,我们通过findViewWithTag的方法获取到需要显示图片的控件,防止因为listview,gridview等控件的复用造成乱串。整个工具就已经完成了,然后我们再把几个方法贴上:
/**
* 将一张图片存储到LruCache中。
*
* @param key
* LruCache的键,这里传入图片的URL地址。
* @param bitmap
* LruCache的键,这里传入从网络上下载的Bitmap对象。
*/
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemoryCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
/**
* 从LruCache中获取一张图片,如果不存在就返回null。
*
* @param key
* LruCache的键,这里传入图片的URL地址。
* @return 对应传入键的Bitmap对象,或者null。
*/
public Bitmap getBitmapFromMemoryCache(String key) {
return mMemoryCache.get(key);
}
/**
* 使用MD5算法对传入的key进行加密并返回。
*/
public String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* 根据传入的uniqueName获取硬盘缓存的路径地址。
*/
public File getDiskCacheDir(Context context, String uniqueName) {
String cachePath;
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
cachePath = context.getExternalCacheDir().getPath();
} else {
cachePath = context.getCacheDir().getPath();
}
return new File(cachePath + File.separator + uniqueName);
}
/**
* 获取当前应用程序的版本号。
*/
public int getAppVersion(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return info.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return 1;
}
/**
* 建立HTTP请求,并获取Bitmap对象。
*
* @param imageUrl
* 图片的URL地址
* @return 解析后的Bitmap对象
*/
private boolean downloadUrlToStream(String urlString,
OutputStream outputStream) {
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(),
8 * 1024);
out = new BufferedOutputStream(outputStream, 8 * 1024);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return true;
} catch (final IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
return false;
}
}
// 压缩图片
public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 源图片的高度和宽度
final int width = options.outWidth;
int inSampleSize = 1;
if (width > reqWidth) {
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高
// 一定都会大于等于目标的宽和高。
inSampleSize = widthRatio;
}
return inSampleSize;
}
然后我们来看一下该如何使用,首先是布局文件
<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"
tools:context="${relativePackage}.${activityClass}" >
<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:focusableInTouchMode="true"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="none"
android:stretchMode="columnWidth"
android:verticalSpacing="13dp" />
</RelativeLayout>
只有一个GridView,然后是item的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical" >
<ImageView
android:id="@+id/product_img"
android:background="#000000"
android:adjustViewBounds="true"
android:src="@drawable/background"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
里面只放一个ImageView,然后我们来看看adapter的实现:
public class MyAdapter extends BaseAdapter {
private Context context;
private List<String> list;
private GridView gridView;
private LayoutInflater mLayoutInflater;
private LoadBitmap loadBitmap;
public MyAdapter(Context context,List<String> list,GridView gridView){
this.context=context;
this.list=list;
this.gridView=gridView;
mLayoutInflater = LayoutInflater.from(this.context);
loadBitmap = LoadBitmap.getInstance(context.getApplicationContext(), gridView);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public String getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(
R.layout.gridview_item, null);
holder = new ViewHolder();
holder.product_img = (ImageView) convertView
.findViewById(R.id.product_img);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.product_img.setTag(list.get(position));
loadBitmap.loadBitmaps(holder.product_img, list.get(position), 300);
return convertView;
}
class ViewHolder {
ImageView product_img;
}
}
这是一个非常标准的BaseAdapter写法,我们在构造方法中,调用LoadBitmap.getInstance(context.getApplicationContext(), gridView);获取实例,其中传人gridview是为了加载完成后根据tag来找到ImageView的,然后在getView中,首先以图片连接为tag加给imageview,然后调用loadBitmaps开始加载图片。
最后我们来看看activity:
public class MainActivity extends Activity {
private GridView gridview;
private MyAdapter adapter;
private List<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview=(GridView) findViewById(R.id.gridview);
list=new ArrayList<String>();
int len = Images.imageThumbUrls.length;
for (int i = 0; i < len; i++) {
list.add(Images.imageThumbUrls[i]);
}
adapter=new MyAdapter(this, list, gridview);
gridview.setAdapter(adapter);
}
}
用法很简单,只需要setAdapter就可以。