編輯:Android 開發實例
遊戲存檔在 Android 上常見有四種做法,先做个整体比较,再逐一實作。
1. SharedPreferences——顧名思義屬於「設定檔」性質的保存,適合結構簡單的小量資料,資料一大就不合適。
2. 檔案串流(FileInputStream / FileOutputStream)——很適合遊戲存檔。能存較大的資料,概念也比資料庫好理解,而且不只能寫進系統內部空間,也能寫到 SD 卡。
3. SQLite——同樣適合遊戲存檔,容量更大、結構更完整,可以放檔案系統、放資料庫,也能丟到 SD 卡。
4. ContentProvider——不推薦用於遊戲存檔。它的強項在於跨應用程式交換資料,而遊戲幾乎不會去讀取外部應用的資料,用它是殺雞用牛刀。
這篇先談前兩種,SQLite 留到下一篇。
優點是簡單、方便,適合快速保存少量資料。限制有兩個:檔案預設存放在 /data/data/com.himi/ 之下,且資料只能在同套件內使用(註:透過 ContentProvider 或設定適當的存取模式,跨套件共享技術上可行,但已超出一般遊戲存檔的需求)。一句話總結:它就是個設定檔,方便但只能裝簡單的東西。
兩篇共用同一份版面配置:兩個 TextView、兩個 EditText、兩個 Button。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/tv_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="保存數據練習!"
android:textSize="20sp" android:textColor="#ff0000" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="請輸入帳號" />
<EditText android:id="@+id/editText_Login"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="請輸入密碼" />
<EditText android:id="@+id/editText_Password"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button android:id="@+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="保存" />
</LinearLayout>
寫入與讀取的程式碼:
public class MainActivity extends Activity implements OnClickListener {
private SharedPreferences sp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 第二個參數是操作模式
sp = getSharedPreferences("Setting_himi", MODE_PRIVATE);
// 啟動時先嘗試讀回上次的資料;找不到時會用第二個參數當預設值
et_login.setText(sp.getString("login", ""));
et_password.setText(sp.getString("password", ""));
}
@Override
public void onClick(View v) {
if (v == btn_save) {
sp.edit()
.putString("login", et_login.getText().toString())
.putString("password", et_password.getText().toString())
.commit(); // 從 edit() 進入編輯狀態,commit() 才真正落地
}
}
}
寫入模式有幾種可選:MODE_PRIVATE 新內容覆蓋舊內容;MODE_APPEND 把新內容接在舊內容之後;MODE_WORLD_READABLE 允許其他應用讀取;MODE_WORLD_WRITEABLE 允許其他應用寫入並覆蓋原資料(後兩者在新版 Android 中已受限制,理解概念即可)。
整個流程就是 edit() → putXxx() → commit(),讀取則是 getXxx(key, 預設值)。就是這麼短。
優點很明確:適合遊戲存檔、能存較大的資料,而且系統內部空間與 SD 卡都能寫。如果你對 SQL 還不熟,這是最省力的選擇。
public class MainActivity extends Activity implements OnClickListener {
private FileOutputStream fos;
private FileInputStream fis;
private DataOutputStream dos;
private DataInputStream dis;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
// 注意:openFileInput 不像 getSharedPreferences 那樣找不到會給預設值,
// 找不到就是 FileNotFoundException,所以 finally 裡一定要收尾
if (this.openFileInput("save.himi") != null) {
fis = this.openFileInput("save.himi");
dis = new DataInputStream(fis);
et_login.setText(dis.readUTF());
et_password.setText(dis.readUTF());
// 讀取順序必須和寫入順序一致,一一對應
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) fis.close(); // 找不到檔案時流不會被實例化,必須先判斷
} catch (IOException e) { e.printStackTrace(); }
}
}
@Override
public void onClick(View v) {
if (v == btn_save) {
try {
fos = this.openFileOutput("save.himi", MODE_PRIVATE);
dos = new DataOutputStream(fos);
dos.writeUTF(et_login.getText().toString());
dos.writeUTF(et_password.getText().toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
dos.close();
fos.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
}
}
為什麼要多一層 DataStream 包裝?除了取得 writeUTF()、readUTF() 這類便利方法之外,主要是方便——直接用 FileStream 讀取時,你得自己開 byte 陣列、跑 while 迴圈把整份內容撈出來,不利於逐筆處理;包裝之後可以一次讀一筆、型別分明。
但這裡有個坑:用 DataStream 寫入字串時,API 規定必須是 UTF-8 編碼,若處理不當會出現亂碼。遇到這種情況,改用 OutputStreamWriter 並在建構時指定編碼即可:
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); String content = EncodingUtils.getString(buffer, "UTF-8"); // 也能做位元組轉字串
從系統內部空間改到 SD 卡,其實只需要動三個地方。
第一,檢查 SD 卡是否存在。
第二,改寫入點。原本的 this.openFileOutput("save.himi", MODE_PRIVATE) 走的是預設路徑,換成自建的 File 物件:
if (Environment.getExternalStorageState() != null) { // 偵測是否有 SD 卡
File path = new File("/sdcard/himi"); // 目錄
File f = new File("/sdcard/himi/save.himi"); // 檔案
if (!path.exists()) path.mkdirs();
if (!f.exists()) f.createNewFile();
fos = new FileOutputStream(f); // 資料寫進 SD 卡
}
第三,改讀取點,同樣從 openFileInput() 換成 new FileInputStream(path)。改了寫入與讀取,finally 區塊裡的判斷條件也要跟著調整,否則會出現空指針。
這裡有個本質差異值得記住:走系統路徑時,檔案不存在 Android 會自動幫你建;寫到 SD 卡則必須自己建目錄、自己建檔案。
最後別忘了在 AndroidManifest.xml 中宣告權限,少了這行,SD 卡寫入一定失敗:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
用 exists() 先判斷再建立,可以避免重複寫入時把檔案又重建一次。更進一步的做法是在程式啟動時就檢查一次、缺什麼補什麼,不過那些屬於優化與簡化,這裡先把原理講通,剩下的變化留給你自己動手。
下一篇接著拆解 SQLite,以及資料庫層級的讀寫操作。
開啟 ListView 側邊快速滾動滑塊:一行屬性搞定 fastScroll
不少開發者不知道 ListView 右側那個快速滾動滑塊(fast scroll thumb)該怎麼啟用,其實只要一行設定。 用 XML 布局的話,在 ListView
Android MediaPlayer:實作含快轉與倒轉的音樂播放器
Android 提供了多種控制音訊/影片播放的方式,其中最常用的是 MediaPlayer 類別。 MediaPlayer 讓我們存取系統內建的媒體播放服務來播放音訊、
MediaPlayer 音訊與視訊播放:搭配 SurfaceView 與 SeekBar 的完整實作
前面的文章把 Android 介面的入門技術介紹得差不多了,相信讀者對常見的 Layout 與 View 都已經有概念。接下來不再談介面,改針對具體功能逐一深入。 本文
Android 應用本地化實作教學
Android 應用往往會在多個國家、各種裝置上運行,使用者來自不同語言背景。要讓應用更具親和力,就必須針對當前語言環境妥善處理文字、數字、檔案等內容,這便是本地化的目標