Android 安卓。应用程序关闭后如何保存用户名和密码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21697172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:56:42  来源:igfitidea点击:

Android. How to save user name and password after the app is closed?

androiduser-interfacepasswordssave

提问by user3182266

I am writing an application with login details (username and password).
I want to make it so that when the user closes the application and starts it again later he/she doesn't have to enter his/her user name and password again.

我正在编写一个带有登录详细信息(用户名和密码)的应用程序。
我想让它在用户关闭应用程序并稍后再次启动时他/她不必再次输入他/她的用户名和密码。

So here is my code so far. It doesn't seem to remember the password nor the username, unfortunately for me:

所以这是我到目前为止的代码。它似乎不记得密码和用户名,对我来说不幸的是:

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mPrefs = getSharedPreferences(PREFS, 0);
    final CheckBox rememberMeCbx = (CheckBox)findViewById(R.id.saveLoginCheckBox);

    boolean rememberMe = mPrefs.getBoolean("rememberMe", false);



    if (android.os.Build.VERSION.SDK_INT > 9)
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    mXmlRpcClient = new XMLRPCClient(mXmlRpcUri);

    // Set up the login form.
    //mUsername = getIntent().getStringExtra(EXTRA_EMAIL);
    mUsernameView = (EditText) findViewById(R.id.username);
    mUsernameView.setText(mUsername);

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView textView, int id,
                        KeyEvent keyEvent) {
                    if (id == R.id.login || id == EditorInfo.IME_NULL) {
                        attemptLogin();
                        return true;
                    }
                    return false;
                }
            });

    mLoginFormView = findViewById(R.id.login_form);
    mLoginStatusView = findViewById(R.id.login_status);
    mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

    findViewById(R.id.sign_in_button).setOnClickListener
    (
            new View.OnClickListener()
            {
                @Override
                public void onClick(View view) 
                {
                    if(rememberMeCbx.isChecked())
                    {
                        attemptLogin(); //function to check if fields are filled correctly
                        saveLoginDetails();
                    }
                    else
                    {
                        attemptLogin();
                        removeLoginDetails();
                    }

                }
            });

    if(rememberMe == true)
    {
        //get previously stored login details
        String login = mPrefs.getString("mUsername", null);
        String upass = mPrefs.getString("mPassword", null);

        if(login != null && upass != null)
        {
            //fill input boxes with stored login and pass
            EditText loginEbx = (EditText)findViewById(R.id.username);
            EditText passEbx = (EditText)findViewById(R.id.password);
            loginEbx.setText(login);
            passEbx.setText(upass);

            //set the check box to 'checked'                
            rememberMeCbx.setChecked(true);
        }
    }
}



/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {
        try {
            mSessionID = (String)mXmlRpcClient.call(mLoginFuncName, mUsername, mPassword);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(false);

        if (success) {
            finish();
            Intent intent = new Intent(LoginActivity.this, MainWindow.class);
            intent.putExtra("SessionID", mSessionID);
            intent.putExtra("XmlRpcUrl", mXmlRpcUrl);
            intent.putExtra("LoginFuncName", mLoginFuncName);
            intent.putExtra("LogoutFuncName", mLogoutFuncName);
            intent.putExtra("GetDevicesFuncName", mGetDevicesFuncName);
            intent.putExtra("SendPositionFuncName", mSendPositionFuncName);
            intent.putExtra("GetSavedTripFunc", mGetSavedTripFunc);             
            startActivity(intent);
        } else {
            mPasswordView
                    .setError(getString(R.string.error_incorrect_password));
            mPasswordView.requestFocus();
        }
    }


}

private void saveLoginDetails()
{
    //fill input boxes with stored login and pass
    EditText loginEbx = (EditText)findViewById(R.id.username);
    EditText passEbx = (EditText)findViewById(R.id.password);
    String login = loginEbx.getText().toString();
    String upass = passEbx.getText().toString();

    Editor e = mPrefs.edit();
    e.putBoolean("rememberMe", true);
    e.putString("login", login);
    e.putString("password", upass);
    e.commit();
}

private void removeLoginDetails()
{
    Editor e = mPrefs.edit();
    e.putBoolean("rememberMe", false);
    e.remove("login");
    e.remove("password");
    e.commit();
}

}

}

Can you tell me what is wrong with my code and how can I improve it so that the user name and password are saved and retrieved after the application is closed and opened again?

你能告诉我我的代码有什么问题吗,我该如何改进它,以便在应用程序关闭并再次打开后保存和检索用户名和密码?

回答by M D

Try this way: defined Preferencesfirst

试试这种方式:Preferences先定义

private static final String PREFS_NAME = "preferences";
private static final String PREF_UNAME = "Username";
private static final String PREF_PASSWORD = "Password";

private final String DefaultUnameValue = "";
private String UnameValue;

private final String DefaultPasswordValue = "";
private String PasswordValue;

And onPause()

onPause()

@Override
public void onPause() {
    super.onPause();
    savePreferences();

}

And onResume()

onResume()

@Override
public void onResume() {
    super.onResume();
    loadPreferences();
     }

And here savePreferences()

和这里 savePreferences()

private void savePreferences() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    // Edit and commit
    UnameValue = edt_username.getText();
    PasswordValue = edt_password.getText();
    System.out.println("onPause save name: " + UnameValue);
    System.out.println("onPause save password: " + PasswordValue);
    editor.putString(PREF_UNAME, UnameValue);
    editor.putString(PREF_PASSWORD, PasswordValue);
    editor.commit();
}

And here loadPreferences()

和这里 loadPreferences()

private void loadPreferences() {

    SharedPreferences settings = getSharedPreferences(PREFS_NAME,
            Context.MODE_PRIVATE);

    // Get value
    UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
    PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
    edt_username.setText(UnameValue);
    edt_password.setText(PasswordValue);
    System.out.println("onResume load name: " + UnameValue);
    System.out.println("onResume load password: " + PasswordValue);
}

回答by LOG_TAG

I high not recommend your logic ! I recommend you toAccountManager APIto authenticate and store the users credentials, or write your own account manager, always use this AccountManagerwhich only stores your auth-token.

我非常不推荐你的逻辑!我建议您对AccountManager API用户凭据进行身份验证和存储,或者编写您自己的帐户管理器,始终使用它只存储您的身份验证令牌。AccountManager

Account Manager's data can also be accessed through a root!

客户经理的数据也可以通过root访问!

For your logic at least try to to use SharedPreferences in secured way otherwise with root access we can get SharedPreferencesdata from the mobile!

对于您的逻辑,至少尝试以安全的方式使用 SharedPreferences,否则通过 root 访问我们可以SharedPreferences从移动设备获取数据!

回答by SMR

OK so far I think your code is correct but you dont know where to implement it.

到目前为止,我认为您的代码是正确的,但您不知道在哪里实现它。

So there should be a point where your login is successful and you want to open another Activityin your app and for that you must be calling an Intent.

所以应该有一个点,您的登录成功并且您想Activity在您的应用程序中打开另一个,为此您必须调用Intent.

Therefore all you need to do is when you fire the Intenton successful login you can call your saveLoginDetails()method like this.

因此,您需要做的就是Intent在成功登录时触发,您可以saveLoginDetails()像这样调用您的方法。

if(*successful login condition*){
    Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
    saveLoginDetails();
    startActivity(intent);
}

and whenever the user logoutyou can implement your removeLoginDetails()method.

每当用户注销时,您都可以实现您的removeLoginDetails()方法。

Hope it helps... Cheers... :)

希望它有帮助...干杯... :)