What is the most appropriate way to store user settings in Android application

后端 未结 14 2081
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 05:38

I am creating an application which connects to the server using username/password and I would like to enable the option \"Save password\" so the user wouldn\'t have to type

相关标签:
14条回答
  • 2020-11-22 06:25

    shared preferences is easiest way to store our application data. but it is possible that anyone can clear our shared preferences data through application manager.so i don't think it is completely safe for our application.

    0 讨论(0)
  • 2020-11-22 06:26

    Using the snippet provided by Richard, you can encrypt the password before saving it. The preferences API however doesn't provide an easy way to intercept the value and encrypt it - you can block it being saved via an OnPreferenceChange listener, and you theoretically could modify it through a preferenceChangeListener, but that results in an endless loop.

    I had earlier suggested adding a "hidden" preference in order to accomplish this. It's definitely not the best way. I'm going to present two other options that I consider to be more viable.

    First, the simplest, is in a preferenceChangeListener, you can grab the entered value, encrypt it, and then save it to an alternative preferences file:

      public boolean onPreferenceChange(Preference preference, Object newValue) {
          // get our "secure" shared preferences file.
          SharedPreferences secure = context.getSharedPreferences(
             "SECURE",
             Context.MODE_PRIVATE
          );
          String encryptedText = null;
          // encrypt and set the preference.
          try {
             encryptedText = SimpleCrypto.encrypt(Preferences.SEED,(String)newValue);
    
             Editor editor = secure.getEditor();
             editor.putString("encryptedPassword",encryptedText);
             editor.commit();
          }
          catch (Exception e) {
             e.printStackTrace();
          }
          // always return false.
          return false; 
       }
    

    The second way, and the way I now prefer, is to create your own custom preference, extending EditTextPreference, @Override'ing the setText() and getText() methods, so that setText() encrypts the password, and getText() returns null.

    0 讨论(0)
提交回复
热议问题