最近在开发应用的一个游戏模块中需缓存大量的网络图片到本地,为图方便直接使用的com.nostra13.universalimageloader提供的图片缓存方法,可在部分内存容量较小手机运行时ImageLoader.loadImage()偶尔抛出OutOfMemoryerror异常进而导致程序崩溃退出。针对该问题我们可以从如下两方法来解决:
1、尽量减少ImageLoader占用的内存避免出现内存溢出的问题
对DisplayImageOptions类使用如下的配置
new DisplayImageOptions.Builder()
.cacheInMemory(false) //设置图片不缓存于内存中
.cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565) //设置图片的质量
.imageScaleType(ImageScaleType.IN_SAMPLE_INT) //设置图片的缩放类型,该方法可以有效减少内存的占用
.build();
2、对错误进行处理
对图片加载方法添加监听事件,对出现的异常进行特定的处理:
imageLoader.loadImage(uri, options, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
// TODO Auto-generated method stub
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
// TODO Auto-generated method stub
switch (failReason.getType()) {
case IO_ERROR:
//handler.sendEmptyMessage();
break;
case DECODING_ERROR:
break;
case NETWORK_DENIED:
break;
case OUT_OF_MEMORY:
break;
case UNKNOWN:
break;
default:
break;
}
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// TODO Auto-generated method stub
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
// TODO Auto-generated method stub
}
});
FailReason为该库中的异常类该类封装了枚举变量FailType,该类的定义如下:
public class FailReason {
private final FailType type;
private final Throwable cause;
public FailReason(FailType type, Throwable cause) {
this.type = type;
this.cause = cause;
}
/** @return {@linkplain FailType Fail type} */
public FailType getType() {
return type;
}
/** @return Thrown exception/error, can be <b>null</b> */
public Throwable getCause() {
return cause;
}
/** Presents type of fail while image loading */
public static enum FailType {
/** Input/output error. Can be caused by network communication fail or error while caching image on file system. */
IO_ERROR,
/**
* Error while
* {@linkplain android.graphics.BitmapFactory#decodeStream(java.io.InputStream, android.graphics.Rect, android.graphics.BitmapFactory.Options)
* decode image to Bitmap}
*/
DECODING_ERROR,
/**
* {@linkplain com.nostra13.universalimageloader.core.ImageLoader#denyNetworkDownloads(boolean) Network
* downloads are denied} and requested image wasn't cached in disc cache before.
*/
NETWORK_DENIED,
/** Not enough memory to create needed Bitmap for image */
OUT_OF_MEMORY,
/** Unknown error was occurred while loading image */
UNKNOWN
}
}