編輯:關於 Android 程式設計
先想一個問題:打開手機設定,進入應用管理,選任一 App,你會看到「清除快取」與「清除資料」兩個按鈕。點擊清除快取時刪掉的是哪裡的資料?清除資料又是刪掉哪裡的資料?讀完本文你會有答案。
Android 開發中經常聽到「記憶體」、「內部儲存」、「外部儲存」三個概念,很多人常把它們搞混。英文裡其實不會混淆:記憶體是 memory,內部儲存是 Internal Storage,外部儲存是 External Storage;但翻譯成中文後前兩者都被簡稱為「記憶體」,於是就亂了。
要分辨它們,最直觀的方式是打開 DDMS 的 File Explorer,裡面有三個資料夾值得注意:data、mnt、storage。
data 資料夾就是我們常說的內部儲存(未 root 的手機無法開啟)。裡面有兩個重點資料夾:
Uploading ...,就是把 apk 上傳到這個資料夾,上傳成功後才開始安裝。shared_prefs:使用 SharedPreferences 持久化的 XML 檔就存在這裡databases:App 的資料庫檔files:一般資料檔cache:快取檔存在這裡的檔案統稱為內部儲存。
外部儲存才是我們日常操作最多的區域,一般是 storage 資料夾(部分機型可能表現在 mnt 下,各家實作略有差異)。
在 storage 中通常有個 sdcard 資料夾,裡面的檔案分兩類:
一般來說我們不會也不該直接操作內部儲存——沒有 root 權限根本無法存取,實際上內部儲存主要由系統維護(程式碼中仍可透過 Context 的 API 訪問)。由於內部空間有限,開發中我們多半操作外部儲存。
Google 官方建議:App 的資料應存放在外部儲存的私有目錄(即該 App 的包名目錄下)。這樣使用者卸載 App 時,相關資料會一併刪除。若你直接在 /storage/sdcard 底下自建一個資料夾,卸載 App 時該資料夾不會被清掉,容易招致使用者反感。
若依路徑特徵區分,可分為兩類:
// 內部儲存 context.getFilesDir(); // data/data/包名/files context.getCacheDir(); // data/data/包名/cache // 外部儲存私有目錄 context.getExternalFilesDir(); // /storage/sdcard/Android/data/包名/files context.getExternalCacheDir(); // /storage/sdcard/Android/data/包名/cache // 外部儲存公有目錄 Environment.getExternalStorageDirectory(); // 根目錄 Environment.getExternalStoragePublicDirectory(type); // 指定類型目錄
其中 getExternalFilesDir() 與 getExternalStoragePublicDirectory() 都需要傳入一個字串參數,用來指定要存取哪個子目錄,參數值採用 Environment 提供的常量。來看看它的原始碼註解:
/** * @param type The type of files directory to return. May be null for * the root of the files directory, or one of the following Environment * constants for a subdirectory: * Environment.DIRECTORY_MUSIC, * Environment.DIRECTORY_PODCASTS, * Environment.DIRECTORY_RINGTONES, * Environment.DIRECTORY_ALARMS, * Environment.DIRECTORY_NOTIFICATIONS, * Environment.DIRECTORY_PICTURES, * Environment.DIRECTORY_MOVIES * * @return The path of the directory holding application files on * external storage. Returns null if external storage is not currently * mounted so it could not ensure the path exists. */ @Nullable public abstract File getExternalFilesDir(@Nullable String type);
可以看到我們能存取 files 目錄下的 Music、Movies、Pictures 等多種子目錄。
小結:開發中不建議往內部儲存寫入過多資料,畢竟空間有限;使用外部儲存時最好把檔案放在私有目錄下,這既方便系統維護,也能避免使用者反感。
點擊「清除資料」時,刪掉的是內部儲存中對應的 files 與 cache 資料夾內容,以及外部儲存中對應的 files 與 cache 資料夾內容。而「清除快取」只會刪掉 cache 部分,files 中的資料會保留下來。
public class SDCardHelper {
// 判斷 SD 卡是否掛載
public static boolean isSDCardMounted() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
// 取得 SD 卡根目錄
public static String getSDCardBaseDir() {
if (isSDCardMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}
// 取得 SD 卡總空間大小(MB)
public static long getSDCardSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
return fs.getBlockCountLong() * fs.getBlockSizeLong() / 1024 / 1024;
}
return 0;
}
// 取得 SD 卡剩餘空間大小(MB)
public static long getSDCardFreeSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
return fs.getFreeBlocksLong() * fs.getBlockSizeLong() / 1024 / 1024;
}
return 0;
}
// 取得 SD 卡可用空間大小(MB)
public static long getSDCardAvailableSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
return fs.getAvailableBlocksLong() * fs.getBlockSizeLong() / 1024 / 1024;
}
return 0;
}
// 存到 SD 卡公有目錄
public static boolean saveFileToSDCardPublicDir(byte[] data, String type, String fileName) {
if (!isSDCardMounted()) {
return false;
}
BufferedOutputStream bos = null;
try {
File file = Environment.getExternalStoragePublicDirectory(type);
bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(bos);
}
return false;
}
// 存到 SD 卡自訂目錄
public static boolean saveFileToSDCardCustomDir(byte[] data, String dir, String fileName) {
if (!isSDCardMounted()) {
return false;
}
BufferedOutputStream bos = null;
try {
File file = new File(getSDCardBaseDir() + File.separator + dir);
if (!file.exists()) {
file.mkdirs(); // 遞迴建立自訂目錄
}
bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(bos);
}
return false;
}
// 存到 SD 卡私有 Files 目錄
public static boolean saveFileToSDCardPrivateFilesDir(byte[] data, String type,
String fileName, Context context) {
if (!isSDCardMounted()) {
return false;
}
BufferedOutputStream bos = null;
try {
File file = context.getExternalFilesDir(type);
bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(bos);
}
return false;
}
// 存到 SD 卡私有 Cache 目錄
public static boolean saveFileToSDCardPrivateCacheDir(byte[] data, String fileName,
Context context) {
if (!isSDCardMounted()) {
return false;
}
BufferedOutputStream bos = null;
try {
File file = context.getExternalCacheDir();
bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(bos);
}
return false;
}
// 把 Bitmap 存到 SD 卡私有 Cache 目錄
public static boolean saveBitmapToSDCardPrivateCacheDir(Bitmap bitmap, String fileName,
Context context) {
if (!isSDCardMounted()) {
return false;
}
BufferedOutputStream bos = null;
try {
File file = context.getExternalCacheDir();
bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
if (fileName != null
&& (fileName.contains(".png") || fileName.contains(".PNG"))) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
} else {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
}
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(bos);
}
return false;
}
// 從 SD 卡讀取檔案
public static byte[] loadFileFromSDCard(String fileDir) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
bis = new BufferedInputStream(new FileInputStream(new File(fileDir)));
byte[] buffer = new byte[8 * 1024];
int c;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baos.close();
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
// 從 SD 卡讀取並解碼為 Bitmap
public static Bitmap loadBitmapFromSDCard(String filePath) {
byte[] data = loadFileFromSDCard(filePath);
if (data != null) {
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
return null;
}
// 取得 SD 卡公有目錄路徑
public static String getSDCardPublicDir(String type) {
return Environment.getExternalStoragePublicDirectory(type).toString();
}
// 取得 SD 卡私有 Cache 目錄路徑
public static String getSDCardPrivateCacheDir(Context context) {
return context.getExternalCacheDir().getAbsolutePath();
}
// 取得 SD 卡私有 Files 目錄路徑
public static String getSDCardPrivateFilesDir(Context context, String type) {
return context.getExternalFilesDir(type).getAbsolutePath();
}
// 判斷檔案是否存在
public static boolean isFileExist(String filePath) {
return new File(filePath).isFile();
}
// 從 SD 卡刪除檔案
public static boolean removeFileFromSDCard(String filePath) {
File file = new File(filePath);
if (file.exists()) {
return file.delete();
}
return false;
}
private static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Activity 深入解析:生命週期、四種狀態與常見特殊用法
Activity 是 Android 四大元件之一,也是我們最直接用來承載畫面的角色。很多人直覺認為「Activity 就是用來顯示 View 的」,這個說法其實只對了一
Android Activity 生命週期與 Intent 導航完整解析
在 Android 開發中,Activity 是使用者最直接接觸到的介面單元。它負責承載畫面、接收操作事件,並透過 Intent 與其他元件協同運作。理解 Activit
Jenkins 建置 Android 專案持續整合:FindBugs 靜態檢查實戰
前言 這篇本來打算跟前面幾篇一起發,結果中間趕上一個版本發布,就擱著了。這幾天手邊的活忙完,剛好接著把「Jenkins 建置 Android 專案持續整合」系列的 Fin
如何找回 Android 手機誤刪的照片
網路上不難看到這類新聞:另一半出了狀況,為了不讓對方發現手機裡的資料,不惜格式化甚至砸毀手機,結果對方拿著那支機器去找資料救援人員,幾天之後大部分檔案原封不動地回來了,只