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

SharedPreferences 深入解析:以「記住密碼」功能為例

編輯:關於 Android 程式設計

SharedPreferences 是 Android 用來存放簡單資料的工具類,可以把它想成一個小型 cookie:以鍵值對形式,把 boolean、int、float、long、String 這些基本型別寫進應用私有目錄(data/data/套件名稱/shared_prefs/)底下自己命名的 XML 檔中。

一、基本概念

它提供的是輕量級的資料儲存方式,讀寫都走 edit() 與 commit()。因為底層就是 XML 檔,不適合存放大量資料或需要查詢條件的結構化內容。

二、常用方法

public abstract boolean contains(String key):檢查指定 key 是否已存在。

edit():取得 Editor 編輯器,所有修改都要透過它進行,且必須呼叫 commit() 才會落地。

getAll():取回全部鍵值對。

getBoolean / getFloat / getInt / getLong / getString:各自接受 key 與預設值兩個參數,取出對應型別的資料。

registerOnSharedPreferenceChangeListener 與 unregisterOnSharedPreferenceChangeListener:註冊與移除資料變動時的回呼。

三、SharedPreferences.Editor

Editor 用於修改 SharedPreferences 的內容。所有操作都是先存在編輯器的批次中,並不會立即寫回原檔案,直到呼叫 commit() 才真正持久化。主要方法有 clear() 清空、remove(String key) 刪除單筆、commit() 提交。

四、實作「記住密碼」

需求很單純:使用者勾選記住密碼後,下次開啟 App 自動帶入帳號密碼;也能勾選自動登入,或一鍵清除已存資料。

登入畫面:

登入成功:

勾選記住密碼並登入一次後,再次開啟時帳密已自動填好:

版面檔 login.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="right"
    android:layout_gravity="right"
    android:background="@drawable/default_bg"
    android:orientation="vertical">

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1">
        <TableRow android:gravity="center" android:layout_gravity="center">
            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/ivlogo" >
            </ImageView>
        </TableRow>
    </TableLayout>

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1">
        <TableRow android:layout_marginTop="100dip">
            <TextView
                android:layout_width="wrap_content"
                android:layout_marginLeft="20dip"
                android:gravity="center_vertical"
                android:layout_height="wrap_content"
                android:id="@+id/tvaccount"
                android:text="帳號:"
                android:textSize="20sp">
            </TextView>
            <EditText
                android:layout_width="70px"
                android:layout_height="wrap_content"
                android:id="@+id/etaccount"
                android:layout_marginRight="20dip"
                android:maxLength="20"></EditText>
        </TableRow>
        <TableRow android:layout_marginTop="10dip">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/tvpw"
                android:layout_marginLeft="20dip"
                android:gravity="center_vertical"
                android:text="密碼:"
                android:textSize="20sp">
            </TextView>
            <EditText
                android:layout_width="70px"
                android:layout_height="wrap_content"
                android:layout_marginRight="20dip"
                android:id="@+id/etpw"
                android:inputType="textPassword"></EditText>
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="5dip"
        android:layout_marginRight="20dip">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvclear"
            android:text="清除Cookies"
            android:textColor="#aa0000"
            android:textSize="12px"></TextView>
    </LinearLayout>

    <TableLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip">
        <TableRow android:gravity="center" android:layout_width="fill_parent">
            <Button
                android:layout_width="100px"
                android:layout_height="wrap_content"
                android:id="@+id/btnlogin"
                android:layout_gravity="center"
                android:text="登錄"></Button>
            <Button
                android:layout_width="100px"
                android:layout_height="wrap_content"
                android:id="@+id/btnexit"
                android:layout_gravity="center"
                android:text="退出"></Button>
        </TableRow>
    </TableLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="25dip">
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/cbrp"
            android:text="記住密碼"
            android:textSize="12px"></CheckBox>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/cbal"
            android:text="自動登錄"
            android:textSize="12px"></CheckBox>
    </LinearLayout>
</LinearLayout>

Activity 程式碼:

package com.wjq;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.wjq.beans.User;
import com.wjq.func.UserMgr;

public class Login extends Activity {
    private EditText etAccount;
    private EditText etPW;
    private Button btnLogin;
    private Button btnExit;
    private CheckBox cbrp;
    private CheckBox cbal;
    private UserMgr userMgr;
    private User user;
    private SharedPreferences sp;
    private TextView tvClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        etAccount = (EditText) findViewById(R.id.etaccount);
        etPW = (EditText) findViewById(R.id.etpw);
        cbrp = (CheckBox) findViewById(R.id.cbrp);
        cbal = (CheckBox) findViewById(R.id.cbal);
        btnLogin = (Button) findViewById(R.id.btnlogin);
        btnExit = (Button) findViewById(R.id.btnexit);
        tvClear = (TextView) findViewById(R.id.tvclear);

        InitConfig();

        cbrp.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp = getSharedPreferences("UserInfo", 0);
                sp.edit().putBoolean("cbrp", isChecked).commit();
            }
        });

        cbal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                sp = getSharedPreferences("UserInfo", 0);
                sp.edit().putBoolean("cbal", isChecked).commit();
            }
        });

        btnLogin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                user = new User(etAccount.getText().toString(), etPW.getText().toString());
                userMgr = new UserMgr();
                Boolean flag = userMgr.CheckUser(user, Login.this);
                if (!flag) {
                    Toast.makeText(Login.this, "用戶驗證錯誤!", 1000).show();
                } else if (cbrp.isChecked()) {
                    // 勾選記住密碼才寫入帳密
                    sp = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("account", etAccount.getText().toString());
                    editor.putString("password", etPW.getText().toString());
                    editor.commit();
                }
            }
        });

        btnExit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });

        tvClear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sp = getSharedPreferences("UserInfo", 0);
                sp.edit().clear().commit();
                InitConfig();
            }
        });
    }

    /** 初始化:把存下來的帳密與勾選狀態回填到畫面 */
    private void InitConfig() {
        sp = getSharedPreferences("UserInfo", 0);
        etAccount.setText(sp.getString("account", null));
        etPW.setText(sp.getString("password", null));
        cbal.setChecked(sp.getBoolean("cbal", false));
        cbrp.setChecked(sp.getBoolean("cbrp", false));
    }
}

寫入與讀出的對照

// 寫入
sp = getSharedPreferences("UserInfo", 0);
sp.edit().putBoolean("cbal", isChecked).commit();

// 讀出
sp = getSharedPreferences("UserInfo", 0);
etAccount.setText(sp.getString("account", null));
etPW.setText(sp.getString("password", null));
cbal.setChecked(sp.getBoolean("cbal", false));
cbrp.setChecked(sp.getBoolean("cbrp", false));

UserInfo 就是 XML 檔名,若檔案不存在會自動建立。流程固定為:透過 edit() 取得 editor,改完呼叫 commit() 提交。

最後必須強調一個安全觀念:SharedPreferences 是明文 XML,任何取得 root 權限或透過 adb backup 的人都可能讀出內容,因此絕不應該直接存放密碼。正確做法是只記住帳號與一組 token,密碼改存到 Keystore 加密後再寫入,或乾脆交給系統的 BiometricPrompt 與 Credential Manager 處理。範例中將 MODE_WORLD_WRITEABLE 改為 MODE_PRIVATE,也是基於同樣的理由。

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