安卓内存清理之Glide

作者: 小王泽哥 | 来源:发表于2016-06-21 10:29 被阅读439次

    项目中使用了glide加载图片
    设置中要求能够清理用户缓存
    计算缓存大小:
    new GetDiskCacheSizeTask().execute(new File(context.getCacheDir(),DiskCache.Factory.DEFAULT_DISK_CACHE_DIR));
    //开启Task任务进行计算
    class GetDiskCacheSizeTask extends AsyncTask<File, Long, Long> {
    @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();
    }

    相关文章

      网友评论

        本文标题:安卓内存清理之Glide

        本文链接:https://www.haomeiwen.com/subject/dqhgdttx.html