android 解决图片大量下载:软引用必须懂4点
对于android中大量图的下载,为了解决oom和显示速度问题,需要深度认识 "软引用",一下主要讲软应用的原理和用法,解决图片oom问题;
ReferenceQueue queue = new ReferenceQueue ();
PhantomReference pr = new PhantomReference (object, queue);
|
if (imageCache.containsKey(imageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(imageUrl);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
}
};
new Thread() {
@Override
public void run() {
Drawable drawable = null;
try {
drawable = getDrawable(imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
} catch (Exception e) {
e.printStackTrace();
}
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
private Drawable getDrawable(String urlString) throws Exception {
if(!NetTools.isWifiConnected(context)){
getImage = DataPreference.getIsAutoGetPicture(context);
}else{
getImage = true;
}
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1).trim();
File cacheFile = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//sdcard已挂载
cacheFile = new File(shopPicInSdcard + fileName);
if (getImage) {
if (!cacheFile.exists() && cacheFile.createNewFile()) {//缓存文件不存在&&创建了该文件,下载缓存图片到Sdcard
InputStream inputStream = getInputStreamFromHttp(urlString);
writeCacheFile2SDCard(cacheFile, readStream(inputStream));
}
return BitmapDrawable.createFromPath(shopPicInSdcard + fileName);
} else {
return null;
}
} else {//只有在没有sdcard的时候才从网上获取数据流
if (getImage) {
InputStream inputStream = getInputStreamFromHttp(urlString);
return Drawable.createFromStream(inputStream, urlString);
} else {
return null;
}
}
}