Cache清除快取資料
阿新 • • 發佈:2019-02-04
主要功能有清除內/外快取,清除資料庫,清除sharedPreference,清除files和清除自定義目錄,主要程式碼如下:
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import java.io.File;
import java.math.BigDecimal;
/**
* @author :huangxianfeng on 2016/6/30.
*本應用資料清除管理器
* 主要功能有清除內/外快取,清除資料庫,清除sharedPreference,清除files和清除自定義目錄
*/
public class DataCleanManager {
private static DataCleanManager instance;
private DataCleanManager(){};
public static DataCleanManager getInstance(){
if(instance == null){
synchronized (DataCleanManager.class){
if (instance == null){
instance = new DataCleanManager();
}
}
}
return instance;
}
/**獲取快取的大小*/
public String getTotalCacheSize(Context context) throws Exception {
long iconPathSize = getFolderSize(new File(SDCardUtil.getInstance().getIconPath()));
long loadPicPathSize = getFolderSize(new File(SDCardUtil.getInstance().getUploadPicPath()));
long cacheSize = getFolderSize(context.getCacheDir());
long deBugSize = getFolderSize(new File(SDCardUtil.getInstance().getDebugPath()));
long downloadPath = getFolderSize(new File(SDCardUtil.getInstance().getDownloadPath()));
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cacheSize += getFolderSize(context.getExternalCacheDir());
}
System.out.println("CacheSize...iconPathSize="+iconPathSize);
System.out.println("CacheSize...loadPicPathSize="+loadPicPathSize);
System.out.println("CacheSize...cacheSize="+cacheSize);
System.out.println("CacheSize...deBugSize="+deBugSize);
System.out.println("CacheSize...downloadPath="+downloadPath);
System.out.println("----------------------------------");
return getFormatSize(cacheSize + deBugSize + iconPathSize + loadPicPathSize+downloadPath);
}
/**清除快取*/
public void clearAllCache(Context context) {
//在此地方進行清除
// BitmapUtil.getInstance().getBitmapUtils().clearMemoryCache();
// BitmapUtil.getInstance().getBitmapUtils().clearCache();
// BitmapUtil.getInstance().getBitmapUtils().clearDiskCache();
CommentDao.getInstance().clearAll();
NoticeDao.getInstance().clearAll();
CivistateDao.getInstance().clearAll();
UserCommentListDao.getInstance().clearData();
deleteFilesByDirectory(new File(SDCardUtil.getInstance().getUploadPicPath()));//清除拍照留下的剪下原圖
deleteFilesByDirectory(new File(SDCardUtil.getInstance().getIconPath()));
deleteFilesByDirectory(new File(SDCardUtil.getInstance().getDownloadPath()));
deleteDir(context.getCacheDir());
deleteDir(new File(SDCardUtil.getInstance().getDebugPath()));
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
deleteDir(context.getExternalCacheDir());
}
}
private 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]));
System.out.println("success" + success + "; = " + dir.getAbsolutePath() + File.separator + children[i]);
if (!success) {
return false;
}
}
}
return dir.delete();
}
/**
* * 清除本應用內部快取(/data/data/com.xxx.xxx/cache) * *
* @param context
*/
public void cleanInternalCache(Context context){
deleteFilesByDirectory(context.getCacheDir());
}
/**
* * 清除本應用所有資料庫(/data/data/com.xxx.xxx/databases) * *
* @param context
*/
public void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/databases"));
}
/**
* * 清除本應用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) *
* @param context
*/
public void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/"
+ context.getPackageName() + "/shared_prefs"));
}
/**
* * 按名字清除本應用資料庫 * *
*
* @param context
* @param dbName
*/
public void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
/**
* * 清除/data/data/com.xxx.xxx/files下的內容 * *
* @param context
*/
public void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
/**
* * 清除外部cache下的內容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
* @param context
*/
public void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
/**
* * 清除自定義路徑下的檔案,使用需小心,請不要誤刪。而且只支援目錄下的檔案刪除 * *
* @param filePath
* */
public void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
/**
* * 清除本應用所有的資料 * *
* @param context
* @param filepath
*/
public void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
if (filepath == null) {
return;
}
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
/**
* * 刪除方法 這裡只會刪除某個資料夾下的檔案,如果傳入的directory是個檔案,將不做處理 * *
* @param directory
*/
private void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()){
for (File item : directory.listFiles()) {
item.delete();
}
}
}
// 獲取檔案
//Context.getExternalFilesDir() --> SDCard/Android/data/你的應用的包名/files/ 目錄,一般放一些長時間儲存的資料
//Context.getExternalCacheDir() --> SDCard/Android/data/你的應用包名/cache/目錄,一般存放臨時快取資料
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 deleteThisPath
* @param filepath
* @return
*/
public void deleteFolderFile(String filePath, boolean deleteThisPath) {
if (!TextUtils.isEmpty(filePath)) {
try {
File file = new File(filePath);
if (file.isDirectory()) {// 如果下面還有檔案
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFolderFile(files[i].getAbsolutePath(), true);
}
}
if (deleteThisPath) {
if (!file.isDirectory()) {// 如果是檔案,刪除
file.delete();
} else {// 目錄
if (file.listFiles().length == 0) {// 目錄下沒有檔案或者目錄,刪除
file.delete();
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 格式化單位
*
* @param size
* @return
*/
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";
}
public String getCacheSize(File file) throws Exception {
return getFormatSize(getFolderSize(file));
}
}
可以根據自己具體情況實現自己的快取清除,有更好的方法,可以留言交流。