在 Android 開發中,合理管理應用數據存儲至關重要。隨著應用運行時間增長,緩存文件、數據庫記錄、SharedPreferences 配置等數據會佔用大量存儲空間,甚至導致應用異常。本文提供一個完整的 DataCleanManager 工具類,涵蓋應用內部存儲的各類數據清理場景,助你輕鬆實現「一鍵清理」功能。
public static void cleanInternalCache(Context context) {
deleteFilesByDirectory(context.getCacheDir());
}
適用於清理圖片緩存、網絡請求緩存等臨時文件。系統在存儲空間不足時可能自動清理此目錄,但主動清理能釋放更多空間。
public static void cleanDatabases(Context context) {
deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/databases"));
}
謹慎使用:此操作將刪除所有 SQLite 數據庫文件,導致用戶數據丟失。通常僅在「恢復出廠設置」或「退出登錄」時使用。
public static void cleanSharedPreference(Context context) {
deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/shared_prefs"));
}
清除所有鍵值對配置,包含用戶登錄狀態、偏好設置等。建議配合特定鍵名刪除使用,避免誤清核心配置。
public static void cleanDatabaseByName(Context context, String dbName) {
context.deleteDatabase(dbName);
}
精準刪除指定數據庫,保留其他數據庫完整,適合模塊化數據管理場景。
public static void cleanFiles(Context context) {
deleteFilesByDirectory(context.getFilesDir());
}
清除應用內部持久化文件,如下載的文檔、生成的報表等。
public static void cleanExternalCache(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
deleteFilesByDirectory(context.getExternalCacheDir());
}
}
針對外部存儲緩存,需檢查 SD 卡掛載狀態。Android 4.4+ 無需權限即可讀寫此目錄,系統會在應用卸載時自動清理。
public static void cleanCustomCache(String filePath) {
deleteFilesByDirectory(new File(filePath));
}
支持清理任意路徑下的文件,使用時需極度小心,確保路徑正確,避免誤刪系統或其他應用文件。
public static void cleanApplicationData(Context context, String... filepath) {
cleanInternalCache(context);
cleanExternalCache(context);
cleanDatabases(context);
cleanSharedPreference(context);
cleanFiles(context);
if (filepath != null) {
for (String filePath : filepath) {
cleanCustomCache(filePath);
}
}
}
綜合清理方案,可傳入額外自定義路徑。建議在「退出登錄」或「重置應用」功能中調用。
private static void deleteFilesByDirectory(File directory) {
if (directory != null && directory.exists() && directory.isDirectory()) {
for (File item : directory.listFiles()) {
item.delete();
}
}
}
僅刪除目錄下的文件,不刪除目錄本身及子目錄。如需深度刪除,可參考 deleteFolderFile 方法。
public static long getFolderSize(File file) throws Exception {
long size = 0;
File[] fileList = file.listFiles();
for (File f : fileList) {
size += f.isDirectory() ? getFolderSize(f) : f.length();
}
return size;
}
public static String getFormatSize(double size) {
// 單位轉換邏輯:Byte → KB → MB → GB → TB
// 使用 BigDecimal 保證精度,保留一位小數
}
可用於在 UI 中顯示「緩存大小:XX MB」,提升用戶體驗。
MediaStore 或 StorageManager// 設置頁面「清理緩存」按鈕點擊事件
btnClearCache.setOnClickListener(v -> {
new Thread(() -> {
long before = DataCleanManager.getFolderSize(getCacheDir());
DataCleanManager.cleanInternalCache(MainActivity.this);
DataCleanManager.cleanExternalCache(MainActivity.this);
long after = DataCleanManager.getFolderSize(getCacheDir());
runOnUiThread(() -> Toast.makeText(this,
"清理完成,釋放 " + DataCleanManager.getFormatSize(before - after),
Toast.LENGTH_SHORT).show());
}).start();
});
合理使用此工具類,能有效控制應用佔用空間,提升用戶留存率。記住:緩存可清,數據須珍,根據業務場景選擇適當清理策略。