说说在 Android 中如何实现记住密码功能

我们使用 SharedPreferences 技术来实现记住密码功能。

我们在 说说在 Android 中如何实现强制下线功能 项目的基础上,修改登录界面的布局:

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="账号:"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/account"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:text="密码:"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:inputType="textPassword" />
    </LinearLayout>

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

        <CheckBox
            android:id="@+id/remember_pwd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="记住密码"
            android:textSize="18sp" />

    </LinearLayout>

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="登录" />
</LinearLayout>

这里添加了 CheckBox 控件来勾选【记住密码】,接着修改 LoginActivity :

ublic class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";

    final String REMEMBER_PWD_PREF = "rememberPwd";
    final String ACCOUNT_PREF = "account";
    final String PASSWORD_PREF = "password";

    /**
     * AES 工具
     */
    private static AES aes = new AES("12345abcdef67890", "1234567890abcdef");

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

        final EditText accountEditText = (EditText) findViewById(R.id.account);
        final EditText passwordEditText = (EditText) findViewById(R.id.password);


        //从 SharedPreferences 中获取【是否记住密码】参数
        final SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isRemember = preference.getBoolean(REMEMBER_PWD_PREF, false);
        final CheckBox rememberPwd = (CheckBox) findViewById(R.id.remember_pwd);

        if (isRemember) {//设置【账号】与【密码】到文本框,并勾选【记住密码】
            accountEditText.setText(preference.getString(ACCOUNT_PREF, ""));
            passwordEditText.setText(aes.decode(preference.getString(PASSWORD_PREF, "")));
            rememberPwd.setChecked(true);
        }

        Button loginBtn = (Button) findViewById(R.id.login);
        loginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = accountEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                if (account.equals("admin") && password.equals("1")) {//登录成功

                    SharedPreferences.Editor editor = preference.edit();
                    if (rememberPwd.isChecked()) {//记住账号与密码
                        editor.putBoolean(REMEMBER_PWD_PREF, true);
                        editor.putString(ACCOUNT_PREF, account);
                        editor.putString(PASSWORD_PREF, aes.encode(password));
                    } else {//清空数据
                        editor.clear();
                    }
                    editor.apply();

                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                } else {//登录失败,弹出提示
                    Toast.makeText(LoginActivity.this, "账号或密码不正确", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
}

这里调用 CheckBox 的 isChecked() 方法来获取勾选状态。如果选中,则表示用户想让应用记住密码,我们就把用户的账号与密码都存入 SharedPreferences 文件;如果没有选中,则直接清除 SharedPreferences 文件中的数据即可。

这里采用 AES 对称加密算法,因为保存在 SharedPreferences 文件中的密码必须加密,否则可能存在安全隐患。之所以必须是对称加密,因为当应用打开登录页时,必须把 SharedPreferences 文件中的密码解密出来,才能真正使用它。

关于 AES 算法的具体实现,请参见这里:
说说如何使用 Java 的原生方法实现 AES 算法


引入 AES 后,可能会出现找不到 sun.misc.BASE64Decodersun.misc.BASE64Encoder
的问题。

因为 Android 没有把这个加入到基础包中,请在这里下载 BASE64Encoder.jar,并引入到 Android Studio 的项目依赖中(File → Project Structure → app → Dependencies)。

加入 BASE64Encoder.jar 的依赖包

运行程序:

记住密码功能演示

第一次点击【记住密码】,登录后再退出。下一次登录就会记住密码啦 O(∩_∩)O~

打开 preferences 文件,可以看到我们的密码已经是加密过的咯:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="password">IXi1FhgynLxu8hzlfB4L4Q==</string>
    <string name="account">admin</string>
    <boolean name="rememberPwd" value="true" />
</map>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 224,764评论 6 522
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 96,235评论 3 402
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 171,965评论 0 366
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 60,984评论 1 300
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 69,984评论 6 399
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,471评论 1 314
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,844评论 3 428
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 40,818评论 0 279
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,359评论 1 324
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,385评论 3 346
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,515评论 1 354
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,114评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,836评论 3 338
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,291评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,422评论 1 275
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,064评论 3 381
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,581评论 2 365

推荐阅读更多精彩内容