編輯:關於 Android 程式設計
專案裡圖片、影片、素材各自散落在不同路徑,久了就成一團亂。這篇示範如何把緩存路徑集中封裝成一個工具類,用列舉管理目錄層級、用 hash 生成檔名,並提供清空指定目錄的能力。
HashMap 中,key 是目錄名稱,value 是完整路徑。DirType 描述目錄與其父目錄的關係,確保新增類型時父子順序不會出錯。
public class IYDCache {
private static final String TAG = "IYDCache";
public static final String CACHE_ROOT = "root_cache";
public static final String CACHE_VIDEO = "video_cache";
public static final String CACHE_IMAGE = "image_cache";
public static final String CACHE_VIDEO_MATERIAL = "material_cache";
private static String ROOT_DIR;
/** 存放所有緩存目錄路徑:key 為 DirType.dirName(),value 為完整路徑 */
private static final HashMap<String, String> mCacheDirBox = new HashMap<>();
/** 第一次因父目錄未初始化而失敗的類型 */
private static final List<DirType> mInitFailedDirType = new ArrayList<>();
/** 檔名前綴,例如 iyd1736054267.mp4 */
private static final String IYD = "iyd";
private static boolean mIsInited = false;
/** 支援的檔案類型 */
public enum FileType {
PNG(".png"), JPG(".jpg"), MP4(".mp4");
final String mSuffix;
FileType(String suffix) { this.mSuffix = suffix; }
public String suffix() { return mSuffix; }
}
/**
* 取得某緩存類型下、對應 url 的完整檔案路徑
* @return 形如 /storage/emulated/0/Android/root_cache/video_cache/iyd1736054267.mp4
*/
public static String getFileNameWithPath(DirType type, String url, FileType fileType) {
return getIYDCacheDirThisType(type) + File.separator
+ generateNameFromUrl(url, fileType);
}
/** 由 url 生成檔名,url 相同則結果必定相同(含副檔名) */
public static String generateNameFromUrl(String url, FileType fileType) {
if (StringUtils.isBlank(url)) return StringUtils.empty();
return IYD + url.hashCode() + fileType.suffix();
}
/** 由物件生成檔名(無副檔名),依賴 equals / hashCode 實作 */
public static String generateNameFromObj(Object obj) {
return IYD + obj.hashCode();
}
/** 取得指定類型的緩存目錄,可能為空字串 */
@Nullable
public static String getIYDCacheDirThisType(DirType type) {
if (!mIsInited) {
throw new IllegalArgumentException(
ResourceUtils.getString(R.string.not_init)
+ " 請確保在 Application 中呼叫了 initCacheDir 方法");
}
String key = type.dirName();
if (mCacheDirBox.containsKey(key)) {
return mCacheDirBox.get(key);
}
LogCus.e(TAG, "沒找到與此對應的目錄 " + key);
return StringUtils.empty();
}
/** 清空指定緩存目錄中的所有內容(背景執行緒) */
public static void clearCacheThisDir(final DirType dirType) {
new Thread(new Runnable() {
@Override public void run() {
FileUtils.clearDir(getIYDCacheDirThisType(dirType));
}
}).start();
}
/** 初始化所有緩存目錄,應在 Application.onCreate 中呼叫 */
public static void initCacheDir(Context context) {
if (!SDCardUtil.isSDCardExist()) {
ToastUtils.show(context, ResourceUtils.getString(R.string.check_memory_is_ok));
return;
}
ROOT_DIR = Environment.getExternalStoragePublicDirectory("Android").getAbsolutePath();
mIsInited = true;
for (DirType dirType : DirType.values()) {
initDirWithParentDirType(dirType);
}
// 再重試一次先前失敗的
for (DirType dirType : mInitFailedDirType) {
initDirWithParentDirType(dirType);
}
}
private static void initDirWithParentDirType(DirType childDir) {
String parentDirPath;
if (childDir == DirType.ROOT) {
if (StringUtils.isBlank(ROOT_DIR)) {
throw new IllegalArgumentException("請先初始化根目錄");
}
parentDirPath = ROOT_DIR;
} else {
parentDirPath = mCacheDirBox.get(childDir.parentDirType().dirName());
}
if (StringUtils.isBlank(parentDirPath) || !parentDirPath.contains(ROOT_DIR)) {
mInitFailedDirType.add(childDir);
return;
}
String dirPath = spliceSeparator(parentDirPath, childDir.dirName());
if (!FileUtils.isFolderExistOrCreateSuccess(dirPath)) {
LogCus.d("初始化文件夾失敗 " + dirPath);
return;
}
mCacheDirBox.put(childDir.dirName(), dirPath);
}
private static String spliceSeparator(String... dir) {
StringBuilder result = new StringBuilder();
for (String s : dir) {
result.append(s).append(File.separator);
}
return result.toString();
}
/** 緩存目錄類型;注意:父目錄一定要寫在子目錄之前 */
public enum DirType {
ROOT(CACHE_ROOT, ROOT_DIR),
VIDEO(CACHE_VIDEO, CACHE_ROOT),
IMAGE(CACHE_IMAGE, CACHE_ROOT),
MATERIAL(CACHE_VIDEO_MATERIAL, CACHE_ROOT);
private final String mDir;
private final String mParentDir;
DirType(String dir, String parentDir) {
this.mDir = dir;
this.mParentDir = parentDir;
}
public String dirName() { return mDir; }
/** 取得父目錄的 DirType;呼叫時務必確認自己不是 ROOT */
public DirType parentDirType() {
for (DirType dirType : DirType.values()) {
if (mParentDir.equals(dirType.dirName())) return dirType;
}
throw new IllegalArgumentException(
"沒找到對應的父文件夾 " + mParentDir
+ ";1、請確保已經添加並定義了 mParentDir;2、請確認呼叫者不是 ROOT");
}
}
}
刪除目錄內容時用遞迴最乾脆,子目錄先清再刪本體:
/** 遞迴移除子目錄及其內容 */
static void purgeDirectory(File dir) {
File[] children = dir.listFiles();
if (children == null) return;
for (File file : children) {
if (file.isDirectory()) purgeDirectory(file);
file.delete();
}
}
/** 清空目錄內容(含子目錄) */
public static void clearDir(String path) {
if (StringUtils.isBlank(path)) return;
purgeDirectory(new File(path));
}
這套設計有兩個容易踩到的點。第一,DirType 的宣告順序有意義——父目錄必須排在子目錄之前,否則首次初始化時子目錄會找不到父路徑(程式碼用重試清單做了補救,但別依賴它)。第二,initCacheDir() 一定要在 Application 的 onCreate 裡提早呼叫,之後各處才能安全地取得路徑;否則 getIYDCacheDirThisType() 會直接拋例外提醒你。
Android NDK 開發入門筆記(一)
接引:Android NDK r7 以後已內建 Cygwin,開發 NDK 時不必再另外下載與設定 Cygwin 環境。 一、在 Eclipse 中設定 NDK 路徑 開
Android 優化:殺死使用者選取的進程後即時刷新 ListView
在前一篇《殺死使用者選取的進程(釋放進程占用的空間)》中,我介紹了如何殺死選取的進程,但遺留一個問題:殺死進程後 ListView 沒有立即刷新。本篇就來解決這個問題,優
深入解析 Android 動態廣播的註冊流程
動態廣播的角色 在 Android 中,BroadcastReceiver 是一套基於發布與訂閱模型的元件通信機制。它可以用於同一進程內的元件互動,也可以透過跨進程方式完
Android layout_weight 權重機制深度解析
layout_weight 是 LinearLayout 中常用的布局屬性,用於按比例分配剩餘空間。很多開發者只把它理解為「比例」,但實際上,它的效果會受到子 View