1. 程式人生 > >SharedPreferences儲存使用者資訊/自動登陸

SharedPreferences儲存使用者資訊/自動登陸

定義全域性變數
private SharedPreferences sp;
sp = getSharedPreferences("login", Context.MODE_PRIVATE);
    if (sp.getBoolean("自動登入", false)) {
        startActivity(new Intent(MainActivity.this, TwoActivity.class));
    } else if (sp.getBoolean("記住密碼", true)) {
        String name = sp.getString("賬號", "");
        String pwd = sp.getString("密碼", "");
        username.setText(name);
        password.setText(pwd);
    }
    
//判斷是否選中記住密碼
if (remember.isChecked()) {
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("賬號", name);
        editor.putString("密碼", pwd);
        editor.putBoolean("記住密碼", true);
        // 5判斷是否自動登入
        //editor.putBoolean("自動登入", true);
        editor.commit();
    }