Android-——sharedPreferences常用记住密码、自动登录

简单的很 直接看代码

 	private EditText name,pass;	
 	 private CheckBox mJi;
    private CheckBox mDeng;

		 name = findViewById(R.id.mName);
        pass = findViewById(R.id.mPass);
         mJi = findViewById(R.id.mCheckJi);
        mDeng = findViewById(R.id.mCheckDeng);

//初始化SharedPreferences
        sharedPreferences = getSharedPreferences("Login", MODE_APPEND);
        edit = sharedPreferences.edit();
        //记住密码 设置一个状态值true/false
        boolean rememberPwd = sharedPreferences.getBoolean("rememberPwd", false);
        if (rememberPwd){//如果为true
            String names = sharedPreferences.getString("names", null);
            String passs = sharedPreferences.getString("passs", null);
            name.setText(names);
            pass.setText(passs);
            mJi.setChecked(true);
        }else{
            mJi.setChecked(false);
        }
        //记住密码
        mJi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mJi.isChecked()) {//如果选中
                   String names = name.getText().toString();
                   String passs = pass.getText().toString();
                    Log.i("AA", "选中"+names);
                    edit.putString("names",names);
                    edit.putString("passs",passs);
                    edit.putBoolean("rememberPwd",true);
                    edit.commit();
                }else if(!mJi.isChecked()){//如果不选中
                    edit.clear();//清空已记住的sharedPreferences
                    edit.commit();
                }
            }
        });
        //自动登录状态判断 设置一个状态值true/false
        boolean zhuang = sharedPreferences.getBoolean("zhuang", false);
        if (zhuang){//跳转
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
        //自动登录
        mDeng.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mDeng.isChecked()) {//如果选中
                    edit.putBoolean("zhuang",true);//给状态值为true
                    edit.commit();//提交
                }
            }
        });

猜你喜欢

转载自blog.csdn.net/Android_Mr_Zhao/article/details/89286336