过程preference前值保存在Android的? [英] Process the value of preference before save in Android?

查看:231
本文介绍了过程preference前值保存在Android的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要前隐窝我的密码保存到本地的android数据库。一切工作正常没有加密,我有preferences.xml等。我怎么能叫我改变preference值之后的函数的(如密码)?这是我的code:

I need to crypt my password before save it to local android database. Everything work fine without encryption, I have preferences.xml and so. How can I call a function after I change value of preference (for example, password) ? Here is my code:

public class Preferences extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);

            // Get the custom preference
            Preference customPref = (Preference) findPreference("pass");

            customPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                String crypto = SimpleCrypto.encrypt("MYSECRETKEY", newValue.toString()); // encrypt
                // Here is where I'm wrong, I guess.
                SharedPreferences settings = getSharedPreferences("preferences", MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("pass", crypto);
                editor.commit();
            });
    }
}

PS:喜欢这个,当我修改密码,它存储的密码不加密

P.S: Like this, when I change password, it stores password without encryption.

推荐答案

我通过扩展底座的EditText preference和加密/解密的密码,有没有这样的:

I did this by extending the base EditTextPreference and encrypting/decrypting the password there:

public class EncryptedEditTextPreference extends EditTextPreference {
  public EncryptedEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public EncryptedEditTextPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public EncryptedEditTextPreference(Context context) {
    super(context);
  }

  @Override
  public String getText() {
    String value = super.getText();
    return SecurityUtils.decrypt(value);
  }

  @Override
  protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
    super.setText(restoreValue ? getPersistedString(null) : (String) defaultValue);
  }

  @Override
  public void setText(String text) {
    if (Utils.isStringBlank(text)) {
      super.setText(null);
      return;
    }
    super.setText(SecurityUtils.encrypt(text));
  }
}

有一些要求,以我个人的事业,但我认为,code是什么,你需要做的pretty的清晰。

There are some calls to my personal utilities, but I think the code is pretty clear in what you need to do.

这篇关于过程preference前值保存在Android的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆