編輯:Android 開發實例
前面連續寫了很多篇 UI 相關的內容,這個系列暫時還沒到收尾的時候,後續我會慢慢把缺的部分補齊。這一篇換個方向,聊聊在 Android 裡非常重要、卻常被初學者忽略的一件事——數據持久化。
任何一款稍微正式一點的 App,都逃不開「把資料留下來」這個需求:使用者改過的設定要記得、離線時看過的內容要能再讀、下載的檔案要落地。Android 為開發者準備了多條實現路徑,本文先把最基礎的兩條講透:內部存儲與 Sdcard(外部)存儲。
Shared Preferences 我另外寫過一篇,但自己對那篇並不算滿意,之後有時間會重寫一份更清楚的版本。這幾天我會把上面幾種方式逐一動手做一遍,今天先從 Internal Storage 與 External Storage 開始。
使用內部存儲時,檔案會被放在應用私有的目錄裡。預設情況下,這些檔案只有當前應用能讀寫,其他 App 無法存取;而當使用者解除安裝本應用時,系統會連帶把這些檔案一起清掉。所以它非常適合存放「只屬於這個 App」的資料。
寫入的流程其實就是最傳統的 Java IO:取得輸出流 → 寫入位元組 → 關閉流。對應到 Android 的 API 是三個步驟:
Context.openFileOutput() 取得 FileOutputStream 物件。write() 把要存的內容寫進串流。close() 關閉串流,確保資料確實落盤。FileOutputStream openFileOutput(String name):以 MODE_PRIVATE 模式開啟名為 name 的檔案。FileOutputStream openFileOutput(String name, int mode):以指定的 mode 開啟檔案。第二個參數 mode 一般直接使用 Context 裡預先定義好的常數:
MODE_APPEND:追加模式,新寫入的內容會接在原有內容之後,而不是覆蓋。MODE_PRIVATE:私有模式(預設值)。檔案已存在則重建並取代原檔,不存在則直接新建。MODE_WORLD_READABLE:讓其他應用可以讀取此檔案。MODE_WORLD_WRITEABLE:讓其他應用可以寫入此檔案。提醒一句:後兩個「開放全域讀寫」的模式在較新的 Android 版本中已被限制使用,這是出於安全模型的收緊。實際開發時,跨應用共享資料請改用 FileProvider 等官方建議的做法。
Context 另外提供了幾個很方便的方法,把它們和上面的寫入流程組合起來,就能完成對檔案的增刪改查(CRUD):
File getFilesDir():取得應用檔案目錄的絕對路徑。boolean deleteFile(String name):刪除指定名稱的檔案。String[] fileList():列出內部存儲路徑下的所有檔名。下面這個例子可以指定檔名與內容來建立檔案,並支援追加、查詢、刪除等操作。先來看布局。
布局代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="file name:" />
<EditText
android:id="@+id/etInternalFilename"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Content:" />
<EditText
android:id="@+id/etInternalContent"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/btnInternalSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save" />
<Button
android:id="@+id/btnInternalDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete" />
<Button
android:id="@+id/btnInternalAppend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="append" />
<Button
android:id="@+id/btnInternalQuery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="query" />
</LinearLayout>
<!-- 以 ListView 展示內部存儲路徑下的所有檔案 -->
<ListView
android:id="@+id/lvInternalData"
android:layout_width="match_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
接著把內部存儲的常見操作集中到一個類裡,之後在 Activity 中只管呼叫就好。
package com.example.internal;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.Context;
public class MyInternalStorage {
// 保存當前調用對象的 Context
private Context context;
public MyInternalStorage(Context context) {
this.context = context;
}
/**
* 保存內容到內部存儲器
* @param filename 檔名
* @param content 內容
*/
public void save(String filename, String content) throws IOException {
File file = new File(context.getFilesDir(), filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
}
/**
* 透過檔名讀取內容
*/
public String get(String filename) throws IOException {
FileInputStream fis = context.openFileInput(filename);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = -1;
while ((len = fis.read(data)) != -1) {
baos.write(data, 0, len);
}
fis.close();
return new String(baos.toByteArray());
}
/**
* 以追加方式在檔案末尾補上內容
*/
public void append(String filename, String content) throws IOException {
FileOutputStream fos = context.openFileOutput(filename, Context.MODE_APPEND);
fos.write(content.getBytes());
fos.close();
}
/**
* 刪除檔案
* @return 是否成功
*/
public boolean delete(String filename) {
return context.deleteFile(filename);
}
/**
* 取得內部存儲路徑下的所有檔名
*/
public String[] queryAllFile() {
return context.fileList();
}
}
Activity 代碼:
package com.example.datastoragedemo;
import java.io.IOException;
import com.example.internal.MyInternalStorage;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class InternalStorageActivity extends Activity {
private EditText etFilename, etContent;
private Button btnSave, btnQuery, btnDelete, btnAppend;
private ListView lvData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_internalstorage);
etFilename = (EditText) findViewById(R.id.etInternalFilename);
etContent = (EditText) findViewById(R.id.etInternalContent);
btnSave = (Button) findViewById(R.id.btnInternalSave);
btnQuery = (Button) findViewById(R.id.btnInternalQuery);
btnDelete = (Button) findViewById(R.id.btnInternalDelete);
btnAppend = (Button) findViewById(R.id.btnInternalAppend);
lvData = (ListView) findViewById(R.id.lvInternalData);
btnSave.setOnClickListener(click);
btnQuery.setOnClickListener(click);
btnDelete.setOnClickListener(click);
btnAppend.setOnClickListener(click);
lvData.setOnItemClickListener(itemClick);
}
private View.OnClickListener click = new OnClickListener() {
@Override
public void onClick(View v) {
MyInternalStorage myInternal;
String filename;
String content;
switch (v.getId()) {
case R.id.btnInternalSave:
filename = etFilename.getText().toString();
content = etContent.getText().toString();
myInternal = new MyInternalStorage(InternalStorageActivity.this);
try {
myInternal.save(filename, content);
Toast.makeText(InternalStorageActivity.this, "保存文件成功",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(InternalStorageActivity.this, "保存文件失敗",
Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnInternalDelete:
filename = etFilename.getText().toString();
myInternal = new MyInternalStorage(InternalStorageActivity.this);
myInternal.delete(filename);
Toast.makeText(InternalStorageActivity.this, "刪除文件成功",
Toast.LENGTH_SHORT).show();
break;
case R.id.btnInternalQuery:
myInternal = new MyInternalStorage(InternalStorageActivity.this);
String[] files = myInternal.queryAllFile();
ArrayAdapter<String> fileArray = new ArrayAdapter<String>(
InternalStorageActivity.this,
android.R.layout.simple_list_item_1, files);
lvData.setAdapter(fileArray);
Toast.makeText(InternalStorageActivity.this, "查詢文件列表",
Toast.LENGTH_SHORT).show();
break;
case R.id.btnInternalAppend:
filename = etFilename.getText().toString();
content = etContent.getText().toString();
myInternal = new MyInternalStorage(InternalStorageActivity.this);
try {
myInternal.append(filename, content);
Toast.makeText(InternalStorageActivity.this, "文件內容追加成功",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(InternalStorageActivity.this, "文件內容追加失敗",
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
// 點擊列表項時,把該檔案的內容讀回來顯示
private OnItemClickListener itemClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) ((ListView) parent).getAdapter();
String filename = adapter.getItem(position);
etFilename.setText(filename);
MyInternalStorage myInternal = new MyInternalStorage(InternalStorageActivity.this);
try {
etContent.setText(myInternal.get(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
執行後先建立三個檔案,再刪掉其中一個,最後按 query 就能看到剩下的清單。用模擬器跑的話,還可以直接在 File Explorer 中查看:/data/data/<package_name>/files/ 就是這些檔案的落腳處。
既然講到內部存儲,就不得不提它的「兄弟」——緩存檔案。cache 的操作方式和內部存儲幾乎一樣,唯一不同的只是取得路徑的方法:改用 Context.getCacheDir()。
但兩者有個關鍵差異:當設備內部空間不足時,Android 會自行刪除這些緩存檔案來騰出可用空間。因此有兩條原則要守住:
外部存儲通常指的就是 Sdcard。相對於內部存儲,它有兩個鮮明的特點:一是不受本應用壟斷,任何取得相應權限的應用都能讀取;二是容量大得多,所以大檔案(圖片、音訊、離線地圖、下載檔)通常都往這裡放。
寫法與內部存儲幾乎一致,但有三件事一定要先處理:
Environment.getExternalStorageState() 取得目前狀態,它回傳一個字串,並與 Environment 中預先定義好的 final 常數比對。只有等於 Environment.MEDIA_MOUNTED 時才算就緒,其他狀態都代表有問題(未掛載、已移除、唯讀等)。Environment.getExternalStorageDirectory() 取得外部存儲的根目錄,再往下拼檔名。AndroidManifest.xml 中加入:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
由於讀寫方式與內部存儲大同小異,這裡只示範一個 save 方法,其餘的 CRUD 就留給各位自行類推。
public void saveToSdcard(String filename, String content) throws IOException {
// 先判斷外部存儲是否已掛載
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
Log.i("main", "本設備有存儲卡!");
File file = new File(Environment.getExternalStorageDirectory(), filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
} else {
Log.i("main", "外部存儲不可用,放棄寫入");
}
}
用模擬器執行時,建立出來的檔案會落在 /mnt/sdcard/ 這個目錄底下。
現在市面上很多 Android 設備本身就自帶 8GB、16GB 甚至更大的存儲空間,同時又保留了 Sdcard 擴充槽。對於這類機型,Environment.getExternalStorageDirectory() 拿到的其實是「內建的對外存儲區」,並不是你插上去的那張記憶卡。若要存取真正擴充的 Sdcard,路徑需要另外處理,不能一概而論。
這一篇把內部存儲、外部存儲與緩存三種檔案式的持久化方式都走過一遍。它們的定位其實很清楚:
如果只是想存幾個設定鍵值,那 Shared Preferences 會更省事;如果需要條件查詢大量結構化記錄,則該輪到 SQLite 上場。選擇合適的工具,比把某一種方式用到極致更重要。
Android APK 的安裝實作完整解析
本文帶大家完整走一遍在 Android 中實現 apk 安裝的流程。首先來看看系統安裝器 PackageInstaller 的清單檔(位於 packages\apps\P
Android 上的 JSON 處理:用四個內建類別拆解資料
JSON 的全名是 JavaScript Object Notation,是一種語言中立的資料交換格式,也是 XML 目前最常被替換的選項。本章說明如何在 Android
Android MediaPlayer 完整教學:打造具備進度條的音樂播放器
Android 提供了多種控制音訊/影片檔案與串流播放的方式,其中最具代表性的是 MediaPlayer 類別。 透過 MediaPlayer,App 得以使用系統內建的
用 JSONObject 拆解天氣資料:Android JSON 解析教學
行動應用要顯示即時資訊,幾乎都得跟遠端伺服器要資料,而 JSON 就是最普遍的那種「通用語言」。它源自 JavaScript 的物件語法,但早已獨立成為一種跨平台的資料交