使用SharedPreferences實現記住密碼和自動登入
阿新 • • 發佈:2019-01-08
今天,來為大家分享一下通過SharedPreferences來實現QQ自動登入與記住密碼:
SharedPreferences是一種輕型的資料儲存方式,它的本質是基於XML檔案儲存key-value鍵值對資料,通常用來儲存一些簡單的配置資訊。其儲存位置在/data/data/<包名>/shared_prefs目錄下。SharedPreferences物件本身只能獲取資料而不支援儲存和修改,儲存修改是通過Editor物件實現。
接下來為大家粘上程式碼:
public class MainActivity extends AppCompatActivity {
private Button btLogin;
private EditText etAccount, etPassword;
private CheckBox cbLogSelf, cbRemPsd;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btLogin = (Button) findViewById(R.id.btLogin);
etAccount = (EditText) findViewById(R.id.etAccount);
etPassword = (EditText) findViewById(R.id.etPassword);
cbLogSelf = (CheckBox) findViewById(R.id.cbLogSelf);
cbRemPsd = (CheckBox) findViewById(R.id.cbRemPsd);
//建立一個私有的名為config的檔案,可以向裡面儲存資料
final SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//定義一個編輯器 可以實現資料的儲存與修改
final SharedPreferences.Editor edit = sp.edit();
intent = new Intent(MainActivity.this, FinishActivity.class);
if (sp.getBoolean("isRem", true)) {
cbRemPsd.setChecked(true );
//通過sp在config中得到賬號與密碼並賦值給輸入框上
etAccount.setText(sp.getString("account", ""));
etPassword.setText(sp.getString("password", ""));
}
//自動跳轉到下一介面
if (sp.getBoolean("isSelf", true)) {
cbLogSelf.setChecked(true);
startActivity(intent);
}
cbRemPsd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(MainActivity.this, "已勾選", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "未勾選", Toast.LENGTH_SHORT).show();
//記住密碼未勾選時,自動登入也不會勾選
cbLogSelf.setChecked(false);
}
}
});
cbLogSelf.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
/**
* 實現自動登入與記住密碼的關聯
* 當點選自動登入時,記住密碼也同時勾選
*/
cbRemPsd.setChecked(true);
}
}
});
btLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//進行非空判斷
String account = etAccount.getText().toString().trim();
String password = etPassword.getText().toString().trim();
if (TextUtils.isEmpty(account) || TextUtils.isEmpty(password)) {
Toast.makeText(MainActivity.this, "賬號與密碼都不能為空", Toast.LENGTH_SHORT).show();
} else {
/**
* 記住密碼
*/
if (cbRemPsd.isChecked()) {
edit.putString("account", etAccount.getText().toString());
edit.putString("password", etPassword.getText().toString());
edit.putBoolean("isRem", true);
edit.commit();
} else {
edit.putString("account", "");
edit.putString("password", "");
edit.putBoolean("isRem", false);
edit.commit();
}
/**
* 自動登入
*/
if (cbLogSelf.isChecked()) {
edit.putBoolean("isSelf", true);
edit.commit();
} else {
edit.putBoolean("isSelf", false);
edit.commit();
}
startActivity(intent);
}
}
});
}
}
分享到這裡 ,希望能幫到大家。