用SharedPreferences实现账号密码的记忆功能和自动登陆功能

//在登陆页面的onCreate方法中
  SharedPreferences sharedPreferences = getSharedPreferences("zhmm", Activity.MODE_PRIVATE);
  username.setText(sharedPreferences.getString("username", null));
  password.setText(sharedPreferences.getString("userpwd", null));
  boolean aptologin = sharedPreferences.getBoolean("aotologin", false);
  if(aptologin == true){
    Intent intent = new Intent();
    intent.putExtra("userName", username.getText().toString());
    intent.putExtra("userPwd", password.getText().toString());
    intent.setClass(getApplicationContext(), Login.class);
    startActivity(intent);
  }

 

//当登陆成功后
    SharedPreferences sharedPreferences = getSharedPreferences("zhmm", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("username", userName);
    editor.putString("userpwd", userPwd);
    editor.putBoolean("aotologin", true);
    editor.commit();

 

//退出账号时
     SharedPreferences sharedPreferences = getSharedPreferences("zhmm", Activity.MODE_PRIVATE);
     SharedPreferences.Editor editor = sharedPreferences.edit();
     editor.putBoolean("aotologin", false);
     editor.commit();

你可能感兴趣的:(android)