最近,我在用户登录时将数据保存在共享首选项中。 现在,如果应用程序已卸载,则共享首选项的数据将被保存。当用户重新安装应用程序时,再次获得该数据就不想再次登录:
android:allowBackup="true"
android:fullBackupOnly="true"
共享的偏好代码
public class SharedPrefManager {
//the constants
private static final String SHARED_PREF_NAME = "simplifiedcodingsharedpref";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_EMAIL = "keyemail";
private static final String KEY_api_token = "api_token";
private static final String KEY_role = "role";
private static final String KEY_ID = "keyid";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//method to let the user login
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getId());
editor.putString(KEY_USERNAME, user.getUsername());
editor.putString(KEY_EMAIL, user.getEmail());
editor.putString(KEY_api_token, user.getapi_token());
editor.putString(KEY_role, user.getrole());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getInt(KEY_ID, -1),
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_EMAIL, null),
sharedPreferences.getString(KEY_api_token, null),
sharedPreferences.getString(KEY_role, null)
);
}
}