編輯:關於 Android 程式設計
開發時常需要把一些資訊保存下來。這篇整理三種把檔案寫進內部儲存與 SD 卡的做法,並比較它們的適用時機。
// Java 開發中常見的保存方式
public static boolean saveUserInfo(String username, String password) {
File file = new File("/data/data/com.ftf.login/info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
// 內容格式:ftf##123
fos.write((username + "##" + password).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
這種寫法把絕對路徑寫死,看起來最直接,但問題也最明顯:路徑與套件名稱綁死,專案一改 package 就失效,而且不太符合 Android 的開發慣例。
傳入 Context 物件,就能把檔案存進應用專屬的資料夾,這才是符合規範的做法:
public static boolean saveUserInfo(Context context, String username, String password) {
try {
File filesDir = context.getFilesDir();
File file = new File(filesDir, "info.txt");
FileOutputStream fos = new FileOutputStream(file);
// 內容格式:ftf##123
fos.write((username + "##" + password).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// 讀回資料
public static Map<String, String> getSavedUserInfo(Context context) {
File filesDir = context.getFilesDir();
File file = new File(filesDir, "info.txt");
try {
FileInputStream fis = new FileInputStream(file);
// 使用 buffer 逐行讀
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String str = br.readLine();
String[] infos = str.split("##");
Map<String, String> map = new HashMap<String, String>();
map.put("username", infos[0]);
map.put("password", infos[1]);
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
這時需要 Environment 來取得外部儲存的路徑。一般機型在 /data/data/sdcard,但部分國產手機與平板的目錄結構並非如此,用 Environment 取得可以確保相容性,也是官方推薦做法:
public static boolean saveUserInfo(Context context, String username, String password) {
try {
// 先確認外部儲存已掛載
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// 取得 SD 卡目錄
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
FileOutputStream fos = new FileOutputStream(file);
// 內容格式:ftf##123
fos.write((username + "##" + password).getBytes());
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
注意原本寫法裡 if (...); 結尾多了一個分號,這是個很容易忽略的低階錯誤——分號讓 if 條件句提前結束,後面的程式碼永遠都會執行。另外,寫入外部儲存需要在 AndroidManifest.xml 註冊 WRITE_EXTERNAL_STORAGE 權限,而且 Android 4.4 之後外部儲存的寫入權限模型有過調整,值得留意。
這種做法最貼近 Android 的設計思路。系統預設有四種檔案權限模式:PRIVATE(私有)、WORLD_READABLE(可讀)、WORLD_WRITEABLE(可寫)、可讀+可寫。而 Context 本身就能直接開啟檔案輸出流,不必自己拼路徑:
public static boolean saveUserInfo(Context context, String username, String password, int mode) {
try {
FileOutputStream fos = null;
// 在上下文的環境中建立檔案
switch (mode) {
case 1:
fos = context.openFileOutput("private.txt", Context.MODE_PRIVATE);
break;
case 2:
fos = context.openFileOutput("readeable.txt", Context.MODE_WORLD_READABLE);
break;
case 3:
fos = context.openFileOutput("writeable.txt", Context.MODE_WORLD_WRITEABLE);
break;
case 4:
fos = context.openFileOutput("public.txt",
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
break;
}
// 內容格式:ftf##123
fos.write((username + "##" + password).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
這也是 Android 開發中保存檔案最推薦的方式:路徑由系統決定,權限由參數控制,程式碼乾淨。
最後提醒兩點。第一,範例中把帳號與密碼以「##」串接後明文存檔,這種做法在真實專案中絕對不可行——敏感資訊應該改用 EncryptedSharedPreferences 或 Keystore 加密,並避免把密碼長期存在裝置上。第二,MODE_WORLD_READABLE 與 MODE_WORLD_WRITEABLE 從 Android 4.2 起已被標記為弃用,在 Android 7.0 之後呼叫會直接拋出 SecurityException,跨應用共享檔案請改用 FileProvider。
Android 自定義標題欄的兩種做法與踩坑記錄
默認的標題欄往往不合設計稿要求——高度、背景色、按鈕位置全都不對。這時候有兩條路:一是改系統標題欄的樣式,二是乾脆不要系統標題欄,自己在佈局裡畫一個。本文兩種都試了,也踩
Android 內建音效均衡器 MusicFx 原始碼分析:預設值從何而來
基於某些需求,作者決定深入研究 Android 內建的音效均衡器 MusicFx,重點在於釐清它那些預設值的由來。網路上討論這個主題的文章並不多,本文以 Android
Android 安全加密系列:HTTPS 通訊與 SSL 憑證實作全解析
系列文章索引 Android 安全加密:對稱加密 Android 安全加密:非對稱加密 Android 安全加密:消息摘要 Message Digest Android
自訂控制項實作:仿卡片堆疊點擊置頂的滑動效果
先看看要模仿的對象是什麼樣子: 行為規則其實只有一條:只有最頂端那張卡片會響應點擊事件。若點到的不是最頂端,就先把被點的卡片移到最前面,再播放移動動畫。技術難點在於子