Android之记住密码与自动登陆实现

以你之姓@ 2022-07-24 12:01 310阅读 0赞

本文主要讲述了利用sharedpreference实现记住密码与自动登陆功能

  1. 根据checkbox的状态存储用户名与密码
  2. 将结果保存在自定义的application中,成为全局变量

布局文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:fitsSystemWindows="true">
  6. <LinearLayout
  7. android:orientation="vertical"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:paddingTop="56dp"
  11. android:paddingLeft="24dp"
  12. android:paddingRight="24dp">
  13. <ImageView android:src="@drawable/logo"
  14. android:layout_width="wrap_content"
  15. android:layout_height="72dp"
  16. android:layout_marginBottom="24dp"
  17. android:layout_gravity="center_horizontal" />
  18. <!-- Email Label -->
  19. <android.support.design.widget.TextInputLayout
  20. android:layout_width="match_parent"
  21. android:layout_height="wrap_content"
  22. android:layout_marginTop="8dp"
  23. android:layout_marginBottom="8dp">
  24. <EditText android:id="@+id/input_email"
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content"
  27. android:inputType="textEmailAddress"
  28. android:hint="Phone" />
  29. </android.support.design.widget.TextInputLayout>
  30. <!-- Password Label -->
  31. <android.support.design.widget.TextInputLayout
  32. android:layout_width="match_parent"
  33. android:layout_height="wrap_content"
  34. android:layout_marginTop="8dp"
  35. android:layout_marginBottom="8dp">
  36. <EditText android:id="@+id/input_password"
  37. android:layout_width="match_parent"
  38. android:layout_height="wrap_content"
  39. android:inputType="textPassword"
  40. android:hint="Password"/>
  41. </android.support.design.widget.TextInputLayout>
  42. <LinearLayout
  43. android:layout_width="match_parent"
  44. android:layout_height="wrap_content"
  45. android:orientation="horizontal"
  46. android:gravity="center_horizontal"
  47. >
  48. <CheckBox
  49. android:id="@+id/rm_pass"
  50. android:layout_width="wrap_content"
  51. android:layout_height="wrap_content"
  52. android:text="记住密码"
  53. android:layout_marginRight="30dp"
  54. android:checked="true"
  55. />
  56. <CheckBox
  57. android:id="@+id/au_login"
  58. android:layout_width="wrap_content"
  59. android:layout_height="wrap_content"
  60. android:text="自动登陆"
  61. android:layout_marginLeft="30dp"
  62. />
  63. </LinearLayout>
  64. <android.support.v7.widget.AppCompatButton
  65. android:id="@+id/btn_login"
  66. android:layout_width="fill_parent"
  67. android:layout_height="wrap_content"
  68. android:layout_marginTop="24dp"
  69. android:layout_marginBottom="24dp"
  70. android:padding="12dp"
  71. android:text="Login"/>
  72. <TextView android:id="@+id/link_signup"
  73. android:layout_width="fill_parent"
  74. android:layout_height="wrap_content"
  75. android:layout_marginBottom="24dp"
  76. android:text="No account yet? Create one"
  77. android:gravity="center"
  78. android:textSize="16dip"/>
  79. </LinearLayout>
  80. </ScrollView>

登陆界面

  1. package com.zj.login;
  2. import android.app.Activity;
  3. import android.app.ProgressDialog;
  4. import android.content.Intent;
  5. import android.content.SharedPreferences;
  6. import android.os.Bundle;
  7. import android.support.v7.app.AppCompatActivity;
  8. import android.util.Log;
  9. import android.util.Patterns;
  10. import android.view.View;
  11. import android.widget.Button;
  12. import android.widget.CheckBox;
  13. import android.widget.EditText;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16. import com.zj.cafetriafood.R;
  17. import butterknife.Bind;
  18. import butterknife.ButterKnife;
  19. /**
  20. * A login screen that offers login via email/password.
  21. */
  22. public class LoginActivity extends AppCompatActivity {
  23. private static final String TAG = "LoginActivity";
  24. private static final int REQUEST_SIGNUP = 0;
  25. private SharedPreferences sp;
  26. @Bind(R.id.input_email) EditText _emailText;
  27. @Bind(R.id.input_password) EditText _passwordText;
  28. @Bind(R.id.btn_login) Button _loginButton;
  29. @Bind(R.id.link_signup) TextView _signupLink;
  30. @Bind(R.id.rm_pass) CheckBox _rmpass;
  31. @Bind(R.id.au_login) CheckBox _aulogin;
  32. @Override
  33. public void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.activity_login);
  36. ButterKnife.bind(this);
  37. sp = this.getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
  38. _loginButton.setOnClickListener(new View.OnClickListener() {
  39. @Override
  40. public void onClick(View v) {
  41. login();
  42. }
  43. });
  44. _signupLink.setOnClickListener(new View.OnClickListener() {
  45. @Override
  46. public void onClick(View v) {
  47. // Start the Signup activity
  48. Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
  49. startActivityForResult(intent, REQUEST_SIGNUP);
  50. }
  51. });
  52. if(sp.getBoolean("ISCHECK", false))
  53. {
  54. _rmpass.setChecked(true);
  55. _emailText.setText(sp.getString("USER_NAME", ""));
  56. _passwordText.setText(sp.getString("PASSWORD", ""));
  57. if(sp.getBoolean("AUTO_ISCHECK", false))
  58. {
  59. //设置默认是自动登录状态
  60. _aulogin.setChecked(true);
  61. //跳转界面
  62. //Intent intent = new Intent(LoginActivity.this,MainActivity.class);
  63. //startActivity(intent);
  64. this.finish();
  65. }
  66. }
  67. }
  68. public void login() {
  69. Log.d(TAG, "Login");
  70. if (!validate()) {
  71. onLoginFailed();
  72. return;
  73. }
  74. _loginButton.setEnabled(false);
  75. final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
  76. R.style.AppTheme_Dark_Dialog);
  77. progressDialog.setIndeterminate(true);
  78. progressDialog.setMessage("Authenticating...");
  79. progressDialog.show();
  80. String email = _emailText.getText().toString();
  81. String password = _passwordText.getText().toString();
  82. // TODO: Implement your own authentication logic here.
  83. Log.i("test","email+password="+email+","+password);
  84. if(!email.equals("123")||!password.equals("123456"))
  85. {
  86. progressDialog.dismiss();
  87. _loginButton.setEnabled(true);
  88. _emailText.setText("");
  89. _passwordText.setText("");
  90. Toast.makeText(getApplication(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
  91. return;
  92. }
  93. if(_rmpass.isChecked())
  94. {
  95. //记住用户名、密码、
  96. SharedPreferences.Editor editor = sp.edit();
  97. editor.putString("USER_NAME", email);
  98. editor.putString("PASSWORD", password);
  99. editor.commit();
  100. sp.edit().putBoolean("ISCHECK", true).commit();
  101. }else
  102. {
  103. sp.edit().putBoolean("ISCHECK", true).commit();
  104. }
  105. if (_aulogin.isChecked())
  106. {
  107. sp.edit().putBoolean("AUTO_ISCHECK", true).commit();
  108. }else
  109. {
  110. sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
  111. }
  112. new android.os.Handler().postDelayed(
  113. new Runnable() {
  114. public void run() {
  115. // On complete call either onLoginSuccess or onLoginFailed
  116. onLoginSuccess();
  117. // onLoginFailed();
  118. progressDialog.dismiss();
  119. }
  120. }, 3000);
  121. }
  122. @Override
  123. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  124. if (requestCode == REQUEST_SIGNUP) {
  125. if (resultCode == RESULT_OK) {
  126. // TODO: Implement successful signup logic here
  127. // By default we just finish the Activity and log them in automatically
  128. this.finish();
  129. }
  130. }
  131. }
  132. @Override
  133. public void onBackPressed() {
  134. // Disable going back to the MainActivity
  135. moveTaskToBack(true);
  136. }
  137. public void onLoginSuccess() {
  138. _loginButton.setEnabled(true);
  139. finish();
  140. }
  141. public void onLoginFailed() {
  142. Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
  143. _loginButton.setEnabled(true);
  144. }
  145. public boolean validate() {
  146. boolean valid = true;
  147. String email = _emailText.getText().toString();
  148. String password = _passwordText.getText().toString();
  149. if (email.isEmpty() || !Patterns.PHONE.matcher(email).matches()) {
  150. _emailText.setError("enter a valid phone number");
  151. valid = false;
  152. } else {
  153. _emailText.setError(null);
  154. }
  155. if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
  156. _passwordText.setError("between 4 and 10 alphanumeric characters");
  157. valid = false;
  158. } else {
  159. _passwordText.setError(null);
  160. }
  161. return valid;
  162. }
  163. }

MainActivity

  1. package com.zj.cafetriafood;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.content.SharedPreferences;
  5. import android.os.Bundle;
  6. import android.support.v7.app.AppCompatActivity;
  7. import android.widget.TextView;
  8. import com.zj.application.MyApplication;
  9. import com.zj.login.LoginActivity;
  10. import butterknife.Bind;
  11. import butterknife.ButterKnife;
  12. public class MainActivity extends AppCompatActivity {
  13. private SharedPreferences sp;
  14. private MyApplication myApplication;
  15. @Bind(R.id.text_user) TextView text_user;
  16. @Override
  17. protected void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. ButterKnife.bind(this);
  21. sp = this.getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
  22. if(sp.getBoolean("AUTO_ISCHECK", false))
  23. {
  24. myApplication= (MyApplication) getApplication();
  25. myApplication.setUsername(sp.getString("USER_NAME",""));
  26. }else
  27. {
  28. Intent intent = new Intent(this, LoginActivity.class);
  29. startActivity(intent);
  30. }
  31. text_user.setText(myApplication.getUsername());
  32. }
  33. }

MyApplication

  1. package com.zj.application;
  2. import android.app.Application;
  3. /**
  4. * Created by jjx on 2016/5/22.
  5. */
  6. public class MyApplication extends Application{
  7. public String getUsername() {
  8. return username;
  9. }
  10. public void setUsername(String username) {
  11. this.username = username;
  12. }
  13. String username;
  14. @Override
  15. public void onCreate() {
  16. super.onCreate();
  17. setUsername("用户名");
  18. }
  19. }

参考链接

Android 记住密码和自动登录界面的实现(SharedPreferences 的用法) - liuyiming_的专栏 - 博客频道 - CSDN.NET

Android中Application类用法 - Harvey Ren - 博客园

Application对象的生命周期是整个程序中最长的,它的生命周期就等于这个程序的生命周期。因为它是全局的单例的,所以在不同的Activity,Service中获得的对象都是同一个对象。所以可以通过Application来进行一些,如:数据传递、数据共享和数据缓存等操作。

在Android中,可以通过继承Application类来实现应用程序级的全局变量,这种全局变量方法相对静态类更有保障,直到应用的所有Activity全部被destory掉之后才会被释放掉。

效果如下

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,310人围观)

还没有评论,来说两句吧...

相关阅读