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

Android 第 8 課:SharedPreferences 保存設定參數的最佳選擇

編輯:關於 Android 程式設計

幾乎每個 App 都需要提供設定畫面:要不要允許陌生人加好友、要不要開啟通知、上次輸入的帳號是什麼。這些「軟體參數」該存哪裡?

Windows 桌面程式習慣寫 ini 檔,J2SE 應用常用 properties 或 XML。那 Android 呢?平台直接提供了 SharedPreferences——一個輕量級的鍵值儲存類別,專門為這類小型設定資料而生。

它背後其實是一個 XML 檔

用 SharedPreferences 存資料,底層會產生一個 XML 檔,位置在:

/data/data/<package name>/shared_prefs/

寫入程式碼:

SharedPreferences sp = getSharedPreferences("itcast", Context.MODE_PRIVATE);
Editor editor = sp.edit();          // 取得編輯器
editor.putString("name", "趙雅智部落格");
editor.putInt("age", 4);
editor.commit();                    // 記得提交,否則不會落地

產生的 itcast.xml 內容長這樣:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="name">趙雅智部落格</string>
    <int name="age" value="4" />
</map>

getSharedPreferences(name, mode) 的兩個參數

  • 第一個參數:檔名。不用自己加副檔名,Android 會自動補上 .xml。
  • 第二個參數:操作模式,共有四種,與前面介紹檔案儲存時提到的相同。若希望背後的 XML 能被其他應用讀寫,可指定 Context.MODE_WORLD_READABLE 與 Context.MODE_WORLD_WRITEABLE。

另外,Activity 還提供 getPreferences(mode),它會預設拿當前類別的類名(不含套件名)當作檔名,省下手動命名的麻煩。

讀取資料

SharedPreferences sp = getSharedPreferences("itcast", Context.MODE_PRIVATE);
// 第二個參數是預設值:key 不存在時就回傳它
String name = sp.getString("name", "");
int age = sp.getInt("age", 1);

那個「預設值」參數常被忽略,但少了它,一旦 key 不存在就會拿到 null 或直接拋出例外,務必養成習慣。

跨應用程式讀取

想讀別的 App 存的 Preference,前提是對方建立時使用了 MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE。假設套件名為 cn.itcast.action 的應用這樣建立:

getSharedPreferences("itcast", Context.MODE_WORLD_READABLE);

其他應用要先建立對方的 Context,再透過它取得 Preference:

Context otherAppsContext = createPackageContext("cn.itcast.action",
        Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sp = otherAppsContext.getSharedPreferences(
        "itcast", Context.MODE_WORLD_READABLE);
String name = sp.getString("name", "");
int age = sp.getInt("age", 0);

如果不走 Context,也可以直接以 XML 檔路徑去讀對方的檔案:

File xmlFile = new File(
    "/data/data/<package name>/shared_prefs/itcast.xml");

不過要留意:這類跨應用公開設定檔的做法在後續 Android 版本已被大幅限制,現行方案應改用 ContentProvider 或 FileProvider 分享資料。

實作範例:用 SP 記住登入帳密

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.lession03_login"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.lession03_login.LoginActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

版面配置

與 SD 卡版本相同的登入畫面:帳號、密碼、ROM / SP / SD 三個單選鈕、登入鈕與「記住密碼」核取方塊。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    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/login_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" >
            <requestFocus />
        </EditText>
    </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/login_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" >

        <RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            tools:ignore="UselessParent" >

            <RadioButton
                android:id="@+id/radio_rom"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="@string/login_rom" />

            <RadioButton
                android:id="@+id/radio_sp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/login_sp" />

            <RadioButton
                android:id="@+id/radio_sd"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/login_sd" />
        </RadioGroup>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_login" />

        <CheckBox
            android:id="@+id/check_remember"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100dp"
            android:text="@string/login_remember" />
    </LinearLayout>

</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">lession03_login</string>
    <string name="login_name">使用者名稱</string>
    <string name="login_pass">密碼</string>
    <string name="login_login">登入</string>
    <string name="login_remember">記住密碼</string>
    <string name="login_rom">ROM 儲存</string>
    <string name="login_sp">SP 儲存</string>
    <string name="login_sd">SD 儲存</string>
</resources>

業務層:LoginService.java

SP 的寫入流程固定三步:getSharedPreferences() 取物件、edit() 取編輯器、commit() 提交。

package com.example.lession03_login.service;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class LoginService {

    private Context context;

    public LoginService(Context context) {
        super();
        this.context = context;
    }

    /**
     * 以 SharedPreferences 儲存帳號與密碼
     */
    public boolean saveBysp(String name, String pass, String fileName) {
        SharedPreferences sp = context.getSharedPreferences(
                fileName, Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putString("name", name);
        editor.putString("pass", pass);
        return editor.commit();
    }
}

界面層:LoginActivity.java

package com.example.lession03_login;

import com.example.lession03_login.service.LoginService;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class LoginActivity extends Activity {

    private EditText edit_name, edit_pass;
    private Button btn_login;
    private Checkable box_remember;
    private LoginService loginService;
    private RadioButton radio_rom, radio_sp, radio_sd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        loginService = new LoginService(this);

        edit_name = (EditText) findViewById(R.id.edit_name);
        edit_pass = (EditText) findViewById(R.id.edit_pass);
        btn_login = (Button) findViewById(R.id.button_login);
        box_remember = (Checkable) findViewById(R.id.check_remember);

        radio_rom = (RadioButton) findViewById(R.id.radio_rom);
        radio_sp = (RadioButton) findViewById(R.id.radio_sp);
        radio_sd = (RadioButton) findViewById(R.id.radio_sd);

        btn_login.setOnClickListener(new MyOnclickListener());

        // 回顯上次儲存的資料
        SharedPreferences preferences =
                this.getSharedPreferences("csdn", Context.MODE_PRIVATE);
        edit_name.setText(preferences.getString("name", ""));
        edit_pass.setText(preferences.getString("pass", ""));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    class MyOnclickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_login:
                    String name = edit_name.getText().toString();
                    String pass = edit_pass.getText().toString();

                    if (TextUtils.isEmpty(name)) {
                        Toast.makeText(LoginActivity.this, "使用者名稱不可為空",
                                Toast.LENGTH_LONG).show();
                        return;
                    } else if (TextUtils.isEmpty(pass)) {
                        Toast.makeText(LoginActivity.this, "密碼不可為空",
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (box_remember.isChecked()) {
                        if (radio_sp.isChecked()) {
                            boolean flag = loginService.saveBysp(name, pass, "csdn");
                            Toast.makeText(LoginActivity.this,
                                    flag ? "儲存成功" : "儲存失敗",
                                    Toast.LENGTH_LONG).show();
                        }
                        // radio_rom / radio_sd 的實作留給讀者自行補上
                    } else {
                        Toast.makeText(LoginActivity.this, "不儲存密碼",
                                Toast.LENGTH_LONG).show();
                    }
                    break;

                default:
                    break;
            }
        }
    }
}

實際預覽

第一次進入時欄位是空的:

輸入帳密並勾選「記住密碼」後按下登入:

手動清空欄位後重新進入:

帳密自動回來了:

再按一次登入,資料被重新寫入:

什麼時候該用 SharedPreferences

  • 適合:設定項、開關狀態、少量基本型別資料(string / int / boolean / float / long / Set)。
  • 不適合:大量資料、需要查詢排序的結構化資料——那是 SQLite 的場地。
  • 密碼等敏感資訊不建議明文存入 SP,正式專案應改用加密或 EncryptedSharedPreferences。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved