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

Android 登入範例完整實作:用 SharedPreferences 記住帳號密碼

編輯:關於 Android 開發

「記住密碼」是登入頁面的常見需求。本文以一個完整範例說明如何用 SharedPreferences 保存使用者輸入的帳號密碼,並在下次啟動時自動回顯。版面檔沿用先前的登入案例,此處不再贅述,重點放在資料讀寫邏輯。

一、封裝 SharedPreferences 讀寫工具類

把讀寫邏輯獨立成 UserInfoUtil,讓 Activity 保持單純:

package com.itheima.login.util;

import java.util.HashMap;
import java.util.Map;

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

public class UserInfoUtil {

    /** 保存使用者名與密碼 */
    public static boolean saveUserInfo_android(Context context, String username, String password) {
        try {
            // 1. 透過 Context 取得 SharedPreferences 物件
            //    name:偏好設定檔名稱;mode:檔案操作模式
            SharedPreferences sp = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);

            // 2. 取得 Editor 物件
            Editor editor = sp.edit();

            // 3. 放入要保存的鍵值
            editor.putString("username", username);
            editor.putString("password", password);

            // 4. 提交
            editor.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /** 讀取使用者名與密碼 */
    public static Map<String, String> getUserInfo_android(Context context) {
        try {
            SharedPreferences sp = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
            // 第二個參數是預設值,當 key 不存在時回傳
            String username = sp.getString("username", "");
            String password = sp.getString("password", "");

            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("username", username);
            hashMap.put("password", password);
            return hashMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

二、Activity 中的登入流程

package com.itheima.login;

import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.itheima.login.util.UserInfoUtil;

public class MainActivity extends Activity implements OnClickListener {

    private EditText et_username;
    private EditText et_password;
    private CheckBox cb_rem;
    private Button bt_login;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;

        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        cb_rem = (CheckBox) findViewById(R.id.cb_rem);
        bt_login = (Button) findViewById(R.id.bt_login);

        // b. 設定按鈕點擊事件
        bt_login.setOnClickListener(this);

        // f. 回顯上次保存的帳號密碼
        Map<String, String> map = UserInfoUtil.getUserInfo_android(mContext);
        if (map != null) {
            et_username.setText(map.get("username"));
            et_password.setText(map.get("password"));
            cb_rem.setChecked(true);   // 同步勾選狀態
        }
    }

    private void login() {
        // c. 取得使用者輸入與勾選狀態
        String username = et_username.getText().toString().trim();
        String password = et_password.getText().toString().trim();
        boolean isrem = cb_rem.isChecked();

        // d. 校驗輸入,不可為空
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(mContext, "用戶名密碼不能為空", Toast.LENGTH_SHORT).show();
            return;
        }

        // 此處省略伺服器請求,預設登入成功

        // e. 若勾選記住密碼,則保存到本機
        if (isrem) {
            boolean result = UserInfoUtil.saveUserInfo_android(mContext, username, password);
            Toast.makeText(mContext,
                    result ? "用戶名密碼保存成功" : "用戶名密碼保存失敗",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(mContext, "無需保存", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                login();
                break;
            default:
                break;
        }
    }
}

三、SharedPreferences 的通用讀寫範式

除了上面的工具類寫法,最直覺的用法是直接寫在 Activity 中:

// (1)保存資料
public void save(View v) {
    String data = et.getText().toString().trim();
    if (TextUtils.isEmpty(data)) {
        Toast.makeText(this, "請輸入數據", 0).show();
        return;
    }
    // 取得 SharedPreferences 物件
    SharedPreferences sp = this.getSharedPreferences("info", Context.MODE_PRIVATE);
    // SharedPreferences 提供了一個編輯器,協助我們保存資料
    Editor editor = sp.edit();
    editor.putString("data", data);
    editor.commit();
}

// (2)讀取資料
public String readData() {
    String data;
    try {
        SharedPreferences sp = this.getSharedPreferences("info", Context.MODE_PRIVATE);
        data = sp.getString("data", null);
    } catch (Exception e) {
        e.printStackTrace();
        data = "";
    }
    return data;
}

四、重點提醒

SharedPreferences 的本質是一個 XML 檔案,適合存放少量、結構簡單的設定值(如是否記住密碼、字型大小、首次引導標記),不適合存放大量資料或需要查詢的結構化資料。

另外,範例中直接以明文保存密碼其實是不安全的做法,正式專案應至少做加鹽雜湊處理,或改用 EncryptedSharedPreferences,甚至只保存 Token 而不保存密碼本身。

最後,commit() 是同步操作會阻塞主執行緒,apply() 則是異步寫入,在無需立即確認結果的場景下優先使用 apply()。

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