我正在编写一个包含登录详细信息(用户名和密码)的应用程序 我想这样做,以便当用户关闭应用程序并稍后再次启动它时,他/她不必再次输入他/她的用户名和密码。
所以这是我的代码到目前为止。不幸的是,它似乎不记得密码和用户名:
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();
}
}
您能告诉我我的代码有什么问题吗?我如何改进它以便在应用程序关闭并再次打开后保存和检索用户名和密码?
答案 0 :(得分:12)
尝试这种方式:首先定义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;
onPause()
@Override
public void onPause() {
super.onPause();
savePreferences();
}
onResume()
@Override
public void onResume() {
super.onResume();
loadPreferences();
}
这里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();
}
这里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);
}
答案 1 :(得分:0)
我高不推荐你的逻辑!我建议您AccountManager API
进行身份验证并存储用户凭据,或者编写自己的帐户管理员,始终使用仅存储您的身份验证令牌的 AccountManager
。
客户经理的数据也可以通过root访问!
对于你的逻辑,至少尝试以安全的方式使用SharedPreferences,否则使用root访问权限我们可以从移动设备获取SharedPreferences
数据!
答案 2 :(得分:0)
好的,到目前为止,我认为您的代码是正确的,但您不知道在哪里实现它。
因此,您的登录成功并且您希望在应用中打开另一个Activity
,因此您必须拨打Intent
。
因此,您需要做的就是在成功登录时触发Intent
,您可以像这样调用saveLoginDetails()
方法。
if(*successful login condition*){
Intent intent=new Intent(CurrentActivity.this,NextActivity.class);
saveLoginDetails();
startActivity(intent);
}
只要用户退出,您就可以实施removeLoginDetails()
方法。
希望它有所帮助......干杯...... :)
答案 3 :(得分:-1)
我建议您将登录详细信息保存到具有简单加密的文件中。
密码= 1234qwer cryptoPassword = 149250351452q113w119e101r114
OnStop SaveLoginData
OnStart ReadLoginData