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

Android 自動登入實作:用 SharedPreferences 記住登入狀態

編輯:關於 Android 程式設計

我們日常用的 App 幾乎都有這個行為:第一次輸入帳號密碼,之後再打開就直接進首頁。QQ 那種「記住帳號」「隱身登入」的勾選,也是同一類機制。這件事其實不需要動用資料庫,SharedPreferences 就綽綽有餘。

思路拆解

整個流程只有兩個動作:

  1. 登入成功時,把一個標記寫進 SharedPreferences;
  2. 進入登入頁時先讀這個標記,如果是已登入狀態就直接跳轉,跳過輸入畫面。

帳號密碼本身仍留在 SQLite 裡,SharedPreferences 只負責「要不要跳過登入」這類輕量設定。

完整程式碼

package com.example.account.login;

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

import com.android.dao.MySQLiteOpenHelper;
import com.example.account.MainActivity;
import com.example.account.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity {

    private EditText e1, e2;
    private SQLiteOpenHelper helper;
    private boolean flag, flag2, flag3;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        TextView textView = (TextView) findViewById(R.id.textView1);
        e1 = (EditText) findViewById(R.id.editText1);
        e2 = (EditText) findViewById(R.id.editText2);

        // 先讀共享參數,判斷是否需要自動登入
        Map<String, Object> map = getMsg("login");
        if (map != null && !map.isEmpty()) {
            if (Boolean.TRUE.equals(map.get("login2"))) {
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
            }
        }

        helper = new MySQLiteOpenHelper(this);
        textView.setText("登錄界面");

        Button loginButton = (Button) findViewById(R.id.button2);
        loginButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (e1.getText().toString().isEmpty() || e2.getText().toString().isEmpty()) {
                    Toast.makeText(LoginActivity.this, "請正確輸入您的帳號密碼",
                                   Toast.LENGTH_SHORT).show();
                    return;
                }

                SQLiteDatabase database = helper.getReadableDatabase();
                Cursor cursor = database.query("user",
                        new String[] {"username", "password"},
                        null, null, null, null, null);

                while (cursor.moveToNext()) {
                    flag  = e1.getText().toString()
                            .equals(cursor.getString(cursor.getColumnIndex("username")));
                    flag2 = e2.getText().toString()
                            .equals(cursor.getString(cursor.getColumnIndex("password")));
                    if (flag && flag2) {
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        Toast.makeText(LoginActivity.this, "登錄成功",
                                       Toast.LENGTH_SHORT).show();

                        flag3 = true;
                        // 登入成功,寫入共享參數
                        Map<String, Object> newMap = new HashMap<String, Object>();
                        newMap.put("login2", flag3);
                        saveMsg("login", newMap);
                    }
                }

                if (!flag3) {
                    Toast.makeText(LoginActivity.this, "您輸入的帳號或密碼有誤",
                                   Toast.LENGTH_SHORT).show();
                }
            }
        });

        Button registerButton = (Button) findViewById(R.id.button1);
        registerButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
            }
        });
    }

    /** 寫入共享參數 */
    public boolean saveMsg(String fileName, Map<String, Object> map) {
        // 一般都用 MODE_PRIVATE,比較安全
        SharedPreferences preferences = getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object object = entry.getValue();
            // 依型別分別寫入
            if (object instanceof Boolean) {
                editor.putBoolean(key, (Boolean) object);
            } else if (object instanceof Integer) {
                editor.putInt(key, (Integer) object);
            } else if (object instanceof Float) {
                editor.putFloat(key, (Float) object);
            } else if (object instanceof Long) {
                editor.putLong(key, (Long) object);
            } else if (object instanceof String) {
                editor.putString(key, (String) object);
            }
        }
        return editor.commit();
    }

    /** 讀取共享參數,這裡用不到 edit */
    public Map<String, ?> getMsg(String fileName) {
        SharedPreferences preferences = getSharedPreferences(fileName, Context.MODE_APPEND);
        return preferences.getAll();
    }
}

幾個值得注意的地方

saveMsg() 之所以要寫得這麼囉嗦,是因為 SharedPreferences 沒有「一次塞進一個 Map」的 API,只能逐筆判型別呼叫對應的 putXxx()。用 entrySet() 搭配 Map.Entry 的 getKey()/getValue() 走訪,是這裡最乾淨的寫法。

另外,commit() 是同步寫入並回傳成敗,apply() 則是異步、不回傳。對登入標記這種小資料,兩者都行;若在主線程寫入大量資料,記得改用 apply() 或丟到背景執行緒。

最後提醒一句:SharedPreferences 是純文字檔,把密碼明文存進去並不安全。實務上應該只存「已登入」的布林旗標或 token,密碼交給伺服器端驗證。

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