android glide 清除缓存,安卓内存清理之Glide

项目中使用了glide加载图片

设置中要求能够清理用户缓存

计算缓存大小:

new GetDiskCacheSizeTask().execute(new File(context.getCacheDir(),DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));

//开启Task任务进行计算

class GetDiskCacheSizeTask extends AsyncTask {

@Override

protected void onPreExecute() {

iView.setCache("计算中...");

}

protected void onProgressUpdate(Long... values) { /* onPostExecute(values[values.length - 1]); */ }

protected Long doInBackground(File... dirs) {

try {

long totalSize = 0;

for (File dir : dirs) {

publishProgress(totalSize);

totalSize += calculateSize(dir);

}

return totalSize;

} catch (RuntimeException ex) {

final String message = String.format("Cannot get size of %s: %s", Arrays.toString(dirs), ex);

}

return 0L;

}

@Override

protected void onPostExecute(Long size) {

String sizeText = Formatter.formatFileSize(context, size);

iView.setCache(sizeText);

}

}

计算代码:

private long calculateSize(File dir) {

if (dir == null) return 0;

if (!dir.isDirectory()) return dir.length();

long result = 0;

File[] children = dir.listFiles();

if (children != null)

for (File child : children)

result += calculateSize(child);

return result;

}

清除缓存

public void clearCache() {

new Thread(new Runnable() {

@Override

public void run() {

Glide.get(BaseApplication.getApp()).clearDiskCache();

BaseApplication.getHandler().post(new Runnable() {

@Override

public void run() {

//清除内存缓存

Glide.get(context).clearMemory();

iView.showToast("清除成功");

new GetDiskCacheSizeTask().execute(new File(context.getCacheDir(), DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));

}

});

}

}).start();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值