注意***如標題主要針對Glide第三方庫加載圖片造成的OOM。
- 如果APP使用中多次多個模塊同時加載或者頻繁加載,由內存頻繁抖動造成OOM,可添加代碼:
android:largeHeap=“true”
<application
android:name=".hotfix.SophixStubApplication"
android:allowBackup="true"
android:icon="@mipmap/im_app_icon_app"
android:label="@string/app_name"
android:supportsRtl="true"
android:largeHeap="true"
android:theme="@style/MyAppTheme">
- 如果滑動容器中圖片條目過多引起OOM,需要多些細節處理
- a.可以設置磁盤緩存的大小
@GlideModule
public class CustomCachingGlideModule extends AppGlideModule {
/** * MemorySizeCalculator類通過考慮設備給定的可用內存和屏幕大小想出合理的默認大小. * 通過LruResourceCache進行緩存。 * @param context * @param builder */
@Override
public void applyOptions(Context context, GlideBuilder builder) {
MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context) .setMemoryCacheScreens(2) .build();
builder.setMemoryCache(new LruResourceCache(calculator.getMemoryCacheSize()));
int diskCacheSizeBytes = 1024 * 1024 * 500; // 100 MB
builder.setDiskCache(new InternalCacheDiskCacheFactory(context, diskCacheSizeBytes));
int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);
builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));
}
@Override
public boolean isManifestParsingEnabled() {
return false;
}
}
在清淡文件application節點下添加代碼引入
<meta-data
android:name="news.dvlp.hostapp.platform.utils.CustomCachingGlideModule"
android:value="GlideModule"/>
- b.:在加載圖片的時候,不要緩存資源,如果可以獲取控件尺寸的話,可以控制加載的尺寸,
Glide.with(paramContext)
.load(paramObject)
.skipMemoryCache(true) //禁止Glide內存緩存
.diskCacheStrategy(DiskCacheStrategy.NONE) //不緩存資源
// .override(500, 500)
.into(paramImageView);
- c.在Adapter中重寫這個方法,當item被隱藏的時候,調用 Glide.with(context).clear(imageView);
@Override
public void onViewRecycled(@NonNull ViewHolder holder) {
super.onViewRecycled(holder);
ImageView imageView=holder.imageView;
if (imageView!=null){
Glide.with(context).clear(imageView);
}
}
- d. 如果是加載本地的圖片資源,需要在頁面銷燬時及時回收
Glide.with(context).clear(imageView);
結尾**通過以上代碼改善了本人在開放中遇到的OOM問題,希望對大家有所幫助。
一個在線圖片壓縮工具:https://tinypng.com/