fresco使用,如果列表图片比多,会特别消耗内存,所以必须进行优化,本文测试使用fresco版本为1.8.1
compile 'com.facebook.fresco:fresco:1.8.1'
// 支持 GIF 动图,需要添加
compile 'com.facebook.fresco:animated-gif:1.8.1'
// 支持 WebP (静态图+动图),需要添加
compile 'com.facebook.fresco:animated-webp:1.8.1'
compile 'com.facebook.fresco:webpsupport:1.8.1'
以下为减少fresco内存占据的几个小步骤:
1.在application初始化中进行内存大小设置:
DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(this)
.setBaseDirectoryPath(new File(AppSettings.AppFilePathDir + "/caches"))
.setBaseDirectoryName("rsSystemPicCache").setMaxCacheSize(200 * ByteConstants.MB)
.setMaxCacheSizeOnLowDiskSpace(100 * ByteConstants.MB)
.setMaxCacheSizeOnVeryLowDiskSpace(50 * ByteConstants.MB)
.setMaxCacheSize(80 * ByteConstants.MB).build();
ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)
.setMainDiskCacheConfig(diskCacheConfig)
.setDownsampleEnabled(true)
.build();
Fresco.initialize(this, config);
同时在onTrimMemory与onLowMemory中清理内存:
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
try {
if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) { // 60
ImagePipelineFactory.getInstance().getImagePipeline().clearMemoryCaches();
}
} catch (Exception e) {
}
}
@Override
public void onLowMemory() {
super.onLowMemory();
try {
ImagePipelineFactory.getInstance().getImagePipeline().clearMemoryCaches();
} catch (Exception e) {
}
}
2.在列表中加载图片时,重置size,避免单张图片过大:
public static DraweeController getLisPicController(String photoUrl) {
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(photoUrl)).
setResizeOptions(
new ResizeOptions(200, 140)).build();
return Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setAutoPlayAnimations(true)
.setTapToRetryEnabled(true).build();
}
//使用Controller加载图片
holder.pic.setController(AppDataUtil.getLisPicController(bean.path + ""));
3.(比较暴力的方式)记录你加载的图片链接,然后在必要的时候强制清除:
protected Set<String> picCacheUris = null;//图片加载链接
在adapter加载图片的时候保存该链接:
@Override
protected void onBind(Holder holder, int position) {
super.onBind(holder, position);
ResourceListItemBean bean = getData().get(position);
tryAddToCacheUrls(bean.path);
}
protected void tryAddToCacheUrls(String url) {
if (!picCacheUris.contains(url + "")) {
picCacheUris.add(url + "");
}
}
然后在页面关闭或者退出等必要时候手动清除内存:
@Override
public void onDestroy() {
super.onDestroy();
tryClearMemoryCache();
}
protected void tryClearMemoryCache() {
if (picCacheUris != null && picCacheUris.size() > 0) {
evictFromMemoryCache(picCacheUris);
picCacheUris.clear();
picCacheUris = null;
}
protected void evictFromDiskCache( Set<String> picCacheUris){
if(picCacheUris!=null) {
for (String url : picCacheUris) {
try {
Uri uri = Uri.parse(url + "");
Fresco.getImagePipeline().evictFromMemoryCache(uri);
} catch (Exception e) {
}
}
}
}