Android——内存篇:清除当前app缓存

来源:互联网 发布:java enum interface 编辑:程序博客网 时间:2024/06/05 01:00

不废话,直接上代码:

一、缓存工具类:

package com.hzzx.meiz.utils;import android.content.Context;import android.os.Environment;import java.io.File;import java.math.BigDecimal;/** * 缓存工具类 */public class CaCheUtil {    public static CaCheUtil caCheUtil;    private Context context;    public static CaCheUtil getInstance(Context context) {        if (caCheUtil == null) {            synchronized (CaCheUtil.class) {                if (caCheUtil == null)                    caCheUtil = new CaCheUtil(context);            }        }        return caCheUtil;    }    public CaCheUtil(Context context) {        this.context = context.getApplicationContext();    }    /**     * 获取当前app缓存大小     *     * @return     * @throws Exception     */    public String getTotalCacheSize() throws Exception {        long cacheSize = getFolderSize(context.getCacheDir());        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            cacheSize += getFolderSize(context.getExternalCacheDir());        }        return getFormatSize(cacheSize);    }    /**     * 清除所有缓存     */    public void clearAllCache() {        deleteDir(context.getCacheDir());        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            deleteDir(context.getExternalCacheDir());        }    }    /**     * 删除目录     *     * @param dir     * @return     */    public boolean deleteDir(File dir) {        if (dir != null && dir.isDirectory()) {            String[] children = dir.list();            for (int i = 0; i < children.length; i++) {                boolean success = deleteDir(new File(dir, children[i]));                if (!success) {                    return false;                }            }        }        return dir.delete();    }    /**     * 获取缓存目录的大小     *     * @param file     * @return     * @throws Exception     */    public long getFolderSize(File file) throws Exception {        long size = 0;        try {            File[] fileList = file.listFiles();            for (int i = 0; i < fileList.length; i++) {                // 如果下面还有文件                if (fileList[i].isDirectory()) {                    size = size + getFolderSize(fileList[i]);                } else {                    size = size + fileList[i].length();                }            }        } catch (Exception e) {            e.printStackTrace();        }        return size;    }    /**     * 格式化单位     *     * @param size     */    public String getFormatSize(double size) {        double kiloByte = size / 1024;        if (kiloByte < 1) {            return size + "Byte";        }        double megaByte = kiloByte / 1024;        if (megaByte < 1) {            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";        }        double gigaByte = megaByte / 1024;        if (gigaByte < 1) {            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";        }        double teraBytes = gigaByte / 1024;        if (teraBytes < 1) {            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";        }        BigDecimal result4 = new BigDecimal(teraBytes);        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";    }}
二、缓存工具类CaCheUtil的使用:

SettingActivity中清理缓存功能:

package com.hzzx.meiz.activity.mine;import android.app.AlertDialog;import android.content.DialogInterface;import android.os.Bundle;import android.os.Handler;import android.widget.Button;import android.widget.CompoundButton;import android.widget.LinearLayout;import android.widget.Switch;import android.widget.TextView;import com.hzzx.meiz.R;import com.hzzx.meiz.base.MyBaseTwoActivity;import com.hzzx.meiz.utils.CaCheUtil;import butterknife.BindView;import butterknife.OnClick;/** * 设置 */public class SettingActivity extends MyBaseTwoActivity {        @BindView(R.id.ll_cache_clear)    LinearLayout llCacheClear;    @BindView(R.id.tv_cache_clear_str)    TextView tvCaCheClearStr;    //清理成功标识    private final int CLEAR_TAG_SUCCESS = 0;    //是否需要清理    private boolean isClear;    private Handler handler = new Handler() {        public void handleMessage(android.os.Message msg) {            switch (msg.what) {                case 0:                    showShortMsg("清理完成");                    tvCaCheClearStr.setText("0KB");            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_setting);        setToolBarTitle("设置");        initView();    }    public void initView() {        String cache;        try {            cache = CaCheUtil.getInstance(SettingActivity.this).getTotalCacheSize();            if (cache.startsWith("0")) {                tvCaCheClearStr.setText("0KB");                isClear = false;            } else {                tvCaCheClearStr.setText(cache);                isClear = true;            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 缓存清理     */    @OnClick(R.id.ll_cache_clear)    public void doCacheClear() {        try {            if (isClear) {                showClearDialog();            } else {                showShortMsg("暂无缓存,不需要清理");            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 显示清除弹窗     */    private void showClearDialog() {        new AlertDialog.Builder(this)                .setTitle("清理缓存")                .setMessage("确认要清除缓存吗?")                .setPositiveButton("确定", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        //        清理缓存                        new Thread(new ClearCache()).start();                    }                })                .setNegativeButton("取消", null)                .show();    }    /**     * 清除缓存     */    private class ClearCache implements Runnable {        @Override        public void run() {            try {                CaCheUtil.getInstance(SettingActivity.this).clearAllCache();                Thread.sleep(1500);                if (CaCheUtil.getInstance(SettingActivity.this).getTotalCacheSize().startsWith("0")) {                    handler.sendEmptyMessage(CLEAR_TAG_SUCCESS);                    isClear = false;                }            } catch (Exception e) {                e.printStackTrace();            }        }    }}


原创粉丝点击