这是昨天改进后的,我测试了下,可以加载图片到5万张,估计5万以上也是没问题的,我只试到5万,其实也没必要这么高,现实中1000左右就差不多了,不过我的应用到100就差不多了,
package com.lanlong.test;
import java.io.File;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class AndrodTestActivity extends Activity {
int number = 50000;
Drawable[] array;
Bitmap [] array2;
private Map<String, SoftReference<Drawable>> imageCache =
new HashMap<String, SoftReference<Drawable>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String iconPath = Environment.getExternalStorageDirectory()
+"/vpn/Bafangtong/image/weixin.png";
// array = new Drawable[number];//BitmapDrawable 一样
// array2 = new Bitmap[number];
File mfile = new File(iconPath);
Log.i("","mfile.exists() = "+mfile.exists());
Drawable draw = null;
long timeBegin = System.currentTimeMillis();
for(int i = 0; i < number; i++)
{
Log.e("", "测试第" + (i+1) + "张图片");
// time = 2second 10000张 8second 50000张 不到1秒, 29ms 100张
// array[i] = getResources().getDrawable(R.drawable.ic_launcher);//1000 ok
// array2[i] = BitmapFactory.decodeFile(iconPath);//max 222
// zoomImg(array2[i], 800, 480);
// array[i] = Drawable.createFromPath(iconPath);//max 221
// array[i] = BitmapDrawable.createFromPath(iconPath);//max 221
//time = 149second ,10000张 ; 1second ,100张 ; 901second ,50000张
addDrawableToCache(""+i, iconPath);
draw = getDrawableByPath(""+i, iconPath);
// array[i] = getBitmapByPath(""+i, iconPath);
Log.i("","draw = "+draw);
try {
// array[i] = Drawable.createFromStream(
// new FileInputStream(iconPath), iconPath);//max 111
// array[i] = BitmapDrawable.createFromStream(
// new FileInputStream(iconPath), iconPath);//max 111
// array2[i] = BitmapFactory.decodeStream(
// new FileInputStream(iconPath));//max 221 ;
// Log.i("", "array["+i+"] = "+array[i]);
} catch (Exception e) {
// TODO: handle exception
}
}
long timeEnd = System.currentTimeMillis();
Log.v("","time = "+(timeEnd - timeBegin)/1000 +" second");
}
public void addDrawableToCache(String id, String path) {
// 强引用的Bitmap对象
Drawable drawable = Drawable.createFromPath(path);
// 软引用的Bitmap对象
SoftReference<Drawable> softDrawable = new SoftReference<Drawable>(drawable);
// 添加该对象到Map中使其缓存
imageCache.put(id, softDrawable);
Log.w("","add, imageCache.size() = "+imageCache.size());
}
public Drawable getDrawableByPath(String id, String path) {
// 从缓存中取软引用的Bitmap对象
SoftReference<Drawable> softDrawable = imageCache.get(id);
// 判断是否存在软引用
if (softDrawable == null) {
return null;
}
// 取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空
Drawable drable = softDrawable.get();
return drable;
}
}