編輯:關於 Android 程式設計
實務開發裡,「把一個檔案寫進手機」幾乎是必備技能。要談寫檔,先把儲存空間的輪廓交代清楚。
內部儲存空間
• RAM:執行用的記憶體,等同電腦的記憶體。
• ROM/內部儲存:長期保存資料的空間,等同電腦的硬碟。
外部儲存空間
• 可插拔的 SD 卡(或模擬的外部私有目錄),相當於行動硬碟、隨身碟。
本文示範如何在「內部儲存」中讀寫檔案。
幾乎每個帶登入介面的 App 都需要把使用者資訊存到本機,就用這個最經典的場景來演練。
版面配置如下:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/ed_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入用戶名"
android:layout_margin="20dp" />
<EditText
android:id="@+id/ed_passwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入密碼"
android:inputType="textPassword"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="40dp"
android:text="自動登錄" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="40dp"
android:onClick="login"
android:text="登錄" />
</RelativeLayout>
</LinearLayout>
按下登入鈕時,若勾選了自動登入,就把帳密寫到應用包名下的 info.txt。
public void login(View v) {
String name = ed_name.getText().toString();
String passwd = ed_passwd.getText().toString();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(passwd)) {
Toast.makeText(this, "用戶名或密碼不能為空", Toast.LENGTH_SHORT).show();
return;
}
if (cb.isChecked()) {
File file = new File(getFilesDir(), "info.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
// 以 name##passwd 的格式寫入
fos.write((name + "##" + passwd).getBytes());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try { fos.close(); } catch (IOException e) { }
}
}
}
Toast.makeText(this, "登錄成功", Toast.LENGTH_SHORT).show();
}
把檔案拉出來看,內容就是我們寫入的字串。
進入 Activity 時,如果檔案存在就讀出來回填。
public void readInfo() {
File file = new File(getFilesDir(), "info.txt");
if (!file.exists()) return;
BufferedReader buffer = null;
try {
FileInputStream fin = new FileInputStream(file);
// 位元組流轉字元流,再包一層緩衝
buffer = new BufferedReader(new InputStreamReader(fin));
String text = buffer.readLine();
String[] s = text.split("##");
ed_name.setText(s[0]);
ed_passwd.setText(s[1]);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (buffer != null) {
try { buffer.close(); } catch (IOException e) { }
}
}
}
上面那種把 /data/data/com.demo.storage/ 硬寫在程式碼裡的做法很危險——打錯一個字母就全盤失效,而且換個包名就報錯。Google 提供了兩個標準 API:
• getFilesDir():回傳 /data/data/你的包名/files,適合放需要長期保存的檔案。
• getCacheDir():回傳 /data/data/你的包名/cache,適合放暫存檔,系統空間不足時會自行清除。
// 舊寫法(不建議)
// File file = new File("/data/data/com.demo.storage/info.txt");
// 標準寫法:getFilesDir() 回傳 File 物件
File file = new File(getFilesDir(), "info.txt");
若想確認實際位置,可到「設定 → 應用程式 → 執行中」找到該進程檢視。
其中的 Clear Data 會清掉整個包名目錄下的內容,Clear Cache 只清 cache 資料夾。理解這兩個按鈕的作用範圍,除錯時判斷「資料為什麼不見了」會快很多。
內部儲存的優點是應用私有、不需任何權限、卸载才會消失;缺點是容量有限且無法讓使用者直接瀏覽。若需要較大檔案或對外分享,就該轉往外部儲存,並記得處理權限與掛載狀態判斷。
Android 修改應用程式捷徑圖示的實作步驟
更換 Android 應用程式啟動捷徑圖示,看似簡單,但常因為快取或既有安裝版本干擾,導致修改後沒有立即反映。以下整理一套可操作的流程。 準備新的圖示資源 先將新的 ic
Android 事件分發機制透視——ViewGroup 篇
當一個 Touch 事件發生時,系統首先會把事件傳遞給當前的 Activity,由 Activity 的 dispatchTouchEvent 來分發事件,源碼如下: p
Android 簡訊驗證碼整合實作(Eclipse 版)
許多 App 都需要透過簡訊驗證碼確認手機號碼,例如註冊、登入或帳號綁定。以 Eclipse 專案為例,整合簡訊驗證碼 SDK 通常包含四個步驟:取得 SDK、導入專案、
Android 呼叫系統相簿選圖:Intent 與結果回傳實作
「從相簿選一張圖」是極常見的需求。做法是發出一個 ACTION_GET_CONTENT 的 Intent 交給系統相簿,等使用者選完後在 onActivityResult