android glide设置缓存大小,android – Glide,当缓存大小超过50 mb时清除缓存

在UI线程外部调用Glide.get(context).clearDiskCache(). (同样考虑clearMemory()以防止在清除磁盘缓存后出现意外)这对我有用

new Thread(new Runnable() {

@Override

public void run() {

Glide.get(MainActivity.this).clearDiskCache();

}

}).start();

There is lot of images in my app so I want to clear cache once cache size is larger than 50 mb.

如果你想要限制50 mb你可以实现滑行模块

import android.annotation.TargetApi;

import android.content.Context;

import android.os.Build;

import android.os.Environment;

import android.os.StatFs;

import android.util.Log;

import com.bumptech.glide.Glide;

import com.bumptech.glide.GlideBuilder;

import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;

import com.bumptech.glide.module.GlideModule;

import com.example.MyApplication;

import java.util.Locale;

public class LimitCacheSizeGlideModule implements GlideModule {

// Modern device should have 8GB (=7.45GiB) or more!

private static final int SMALL_INTERNAL_STORAGE_THRESHOLD_GIB = 6;

private static final int DISK_CACHE_SIZE_FOR_SMALL_INTERNAL_STORAGE_MIB = 50*1024*1024;

@Override

public void applyOptions(Context context, GlideBuilder builder) {

if (MyApplication.from(context).isTest()) return; // NOTE: StatFs will crash on robolectric.

double totalGiB = getTotalBytesOfInternalStorage() / 1024.0 / 1024.0 / 1024.0;

Log.i(String.format(Locale.US, "Internal Storage Size: %.1fGiB", totalGiB));

if (totalGiB < SMALL_INTERNAL_STORAGE_THRESHOLD_GIB) {

Log.i("Limiting image cache size to " + DISK_CACHE_SIZE_FOR_SMALL_INTERNAL_STORAGE_MIB + "MiB");

builder.setDiskCache(new InternalCacheDiskCacheFactory(context, DISK_CACHE_SIZE_FOR_SMALL_INTERNAL_STORAGE_MIB));

}

}

@Override

public void registerComponents(Context context, Glide glide) {

}

private long getTotalBytesOfInternalStorage() {

// https://stackoverflow.com/a/4595449/1474113

StatFs stat = new StatFs(Environment.getDataDirectory().getPath());

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {

return getTotalBytesOfInternalStorageWithStatFs(stat);

} else {

return getTotalBytesOfInternalStorageWithStatFsPreJBMR2(stat);

}

}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)

private long getTotalBytesOfInternalStorageWithStatFs(StatFs stat) {

return stat.getTotalBytes();

}

@SuppressWarnings("deprecation")

private long getTotalBytesOfInternalStorageWithStatFsPreJBMR2(StatFs stat) {

return (long) stat.getBlockSize() * stat.getBlockCount();

}

}

然后在你的清单中添加它

...

android:name="YourPackageNameHere.LimitCacheSizeGlideModule"

android:value="GlideModule" />

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值