我正在使用 SharedPreferences 来保存凭据,这可以正常工作,但是当应用程序被杀死时,会要求用户再次登录。
保存凭据后,如果应用程序被终止,则不应要求用户登录。任何帮助,将不胜感激。
public class MyActivity extends Activity {
public static final String PREFS_NAME = "myFile";
private String user;
private String userName;
@Override
public void onRestart(){
super.onRestart();
userName = null;
user=null;
//Retrieve the preferences.
SharedPreferences credentials = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
user = credentials.getString(userName, null);
//Check for stored preferences.
if (user!=null) {
Intent j = new Intent(getApplicationContext(), MainActivity.class);
startActivity(j);
finish();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.layout_login_new);
//Initializing the fields from XML layout.
final Button login_btn = (Button) findViewById(R.id.btnLogin);
//Retrieve the preferences.
SharedPreferences credentials = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
final SharedPreferences.Editor editor = credentials.edit();
userName = null;
user=null;
//retrieve the stored values.
user = credentials.getString(userName, null);
//Check for stored preferences.
if (user!=null){
Intent j = new Intent(getApplicationContext(), MainActivity.class);
j.putExtra("user_name", user);
startActivity(j);
finish();
}
//Listener for the login button.
login_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent j = new Intent(getApplicationContext(), MainActivity.class);
// Verify the username and password.
if (
(username_login.getText().toString()).equals("test")&&(password_login.getText().toString()).equals("test")){
//Store the credentials in sharedPreferences.
user=username_login.getText().toString();
editor.putString(userName, username_login.getText().toString()).commit();
j.putExtra("user_name", user);
startActivity(j);
finish();
}
else{
Display_error_msg();
}
}
});