Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手實作:Android 登入資料的三種儲存方式

編輯:關於 Android 程式設計

在多數 App 裡,「記住密碼」都是標配功能,而它背後其實牽涉到資料要存在哪裡、怎麼存的問題。Android 給了我們好幾條路可以走,其中最常見的三種分別是:手機內部儲存空間(ROM)、SharedPreferences,以及外部的 SD 卡。本文就以一個登入頁面為例,把這三種做法完整走一遍。

先來看畫面怎麼排

登入頁需要一個帳號欄、一個密碼欄、一顆登入鈕,再加上「記住密碼」的勾選框,最後用一組單選按鈕讓使用者挑選要用哪一種方式來保存資料。以 LinearLayout 逐層堆疊即可:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- 帳號 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/view_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_name" />
        <EditText
            android:id="@+id/edit_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName" />
    </LinearLayout>

    <!-- 密碼 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/view_pass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_pass" />
        <EditText
            android:id="@+id/edit_pass"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPassword" />
    </LinearLayout>

    <!-- 登入鈕與記住密碼 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/btn_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_login" />
        <CheckBox
            android:id="@+id/cbx_rember"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:text="@string/text_rember" />
    </LinearLayout>

    <!-- 選擇儲存方式的單選群組 -->
    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <RadioButton android:id="@+id/radio_rom" android:checked="true" android:text="@string/rom" />
        <RadioButton android:id="@+id/radio_sp" android:text="@string/sp" />
        <RadioButton android:id="@+id/radio_sd" android:text="@string/sd" />
    </RadioGroup>
</LinearLayout>

字串資源

把畫面上出現的文字抽到 strings.xml,日後要改文案或做多語系都會輕ylib許多:

<resources>
    <string name="app_name">用戶登錄三種數據存儲方式</string>
    <string name="text_name">用戶名:</string>
    <string name="text_pass">密碼:</string>
    <string name="text_login">登陸</string>
    <string name="text_rember">記住密碼</string>
    <string name="rom">rom存儲</string>
    <string name="sp">sp存儲</string>
    <string name="sd">sd存儲</string>
</resources>

把儲存邏輯抽到服務層

為了讓 Activity 保持乾淨,我們把三種儲存與讀取的做法全部封裝進 FileService。內部儲存的部分用 openFileOutput() 取得檔案輸出流,支援多種模式:

public boolean saveToRom(String name, String pass, String fileName) throws IOException {
    try {
        FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
        String result = name + ":" + pass;
        fos.write(result.getBytes());
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

除了私有的 MODE_PRIVATE,程式碼裡還示範了 MODE_APPEND(追加)、MODE_WORLD_READABLE(可讀)與 MODE_WORLD_WRITEABLE(可寫)等模式,寫法大同小異,只是把寫入前的模式參數換掉即可。

SharedPreferences 的版本就更直覺了,透過 Editor 一個個 put 進去,最後 commit:

public boolean saveBytsp(String name, String pass, String fileName) {
    SharedPreferences preferences = context.getSharedPreferences(fileName, context.MODE_PRIVATE);
    Editor editor = preferences.edit();
    editor.putString("name", name);
    editor.putString("pass", pass);
    editor.putInt("age", 8);
    editor.putBoolean("flag", true);
    return editor.commit();
}

而寫入 SD 卡之前,記得先確認裝置真的有掛載可讀寫的外部儲存:

public boolean saveToSDCard(String name, String pass, String fileName) {
    if (Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)) {
        File sdCardDir = Environment.getExternalStorageDirectory();
        File file = new File(sdCardDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            String result = name + ":" + pass;
            fos.write(result.getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    } else {
        Toast.makeText(context, "手機不擁有SDCard", Toast.LENGTH_LONG).show();
    }
    return true;
}

讀取時,把整份檔案內容取出後,用冒號把帳號與密碼拆開,再塞進 Map 回傳:

public Map<String, String> readFileSDcard(String fileName) {
    Map<String, String> map = null;
    try {
        File sdcardDir = Environment.getExternalStorageDirectory();
        File file = new File(sdcardDir, fileName);
        FileInputStream fis = new FileInputStream(file);
        String value = StreamTools.getValue(fis);
        String values[] = value.split(":");
        if (values.length > 0) {
            map = new HashMap<String, String>();
            map.put("name", values[0]);
            map.put("pass", values[1]);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}

順手做個小工具

把「讀完 InputStream 並轉成字串」這段常見動作抽成 StreamTools,之後到處都能 reuse:

public class StreamTools {
    public static String getValue(FileInputStream fis) throws IOException {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 1;
        while ((length = fis.read(buffer)) != -1) {
            stream.write(buffer, 0, length);
        }
        stream.flush();
        stream.close();
        return stream.toString();
    }
}

把一切串起來的 Activity

在 onCreate 裡先找出各元件、綁好監聽器,並嘗試從 SD 卡把上次存的帳密讀出來做「回顯」;按下登入鈕時,則依勾選與單選的狀態決定要呼叫哪一種儲存方法:

Map<String, String> map = fileService.readFileSDcard("csdnsdcard.txt");
if (map != null) {
    edit_name.setText(map.get("name"));
    edit_pass.setText(map.get("pass"));
}
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
    Toast.makeText(LoginActivity.this, "用戶名或者密碼不能為空", Toast.LENGTH_LONG).show();
    return;
}
if (box_remember.isChecked()) {
    if (radio_sp.isChecked()) {
        boolean flag = fileService.saveBytsp(name, pass, "csdn");
        // 依 flag 提示成功或失敗
    } else if (radio_sd.isChecked()) {
        boolean flag = fileService.saveToSDCard(name, pass, "csdnsdcard.txt");
        // 依 flag 提示成功或失敗
    }
}

別忘了權限

只要會碰觸外部儲存,就一定要在 AndroidManifest.xml 開好權限,否則執行期會直接噴例外:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

小結

以內部儲存寫出的檔案,會落在 /data/data/<package name>/files 這個屬於 App 私有的目錄裡,以 txt 形式存在。三種方式各有取捨:內部儲存最私密、SharedPreferences 最適合少量鍵值資料、SD 卡則適合放大檔,但資料公開且需要额外權限。挑哪一種,取決於你的資料特性與安全需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved