问题
Hi i want to maintain some sessions in my application. May i use shared preference to maintain it? I not then plz suggest me the proper way with the simple example.
回答1:
Maybe you should make use of server to maintain sessions. Because as you have suggested here, using shared preference, you are leaving the option of clearing the preferences from memory to the user. So in this case if the user clears your app data, then your concept of sessions fails.
回答2:
Yes, you can use the shared preferences.
For example, to save username, password and session ID, you can:
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
SharedPreferences.Editor edit = pref.edit();
edit.putString("User Name", username);
edit.putString("Password", password);
edit.putInt("Session ID", session_id);
edit.commit();
And to get them:
SharedPreferences pref = myContexy.getSharedPreferences("Session Data", MODE_PRIVATE);
username = pref.getString("User Name", "");
password = pref.getString("Password", "");
session_id = pref.getInt("Session ID", 0);
This is just an example, it is better to use string constants instead of just "User Name" etc.
回答3:
You're probably looking onSaveInstanceState. It can be used to save the state of a page and restore it later
来源:https://stackoverflow.com/questions/7173287/may-mainting-the-session-using-shared-preference-in-android