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

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

布局文件

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true"> <LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp"> <ImageView android:src="@drawable/logo"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal" /> <!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="@+id/input_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Phone" />
</android.support.design.widget.TextInputLayout> <!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="@+id/input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
>
<CheckBox
android:id="@+id/rm_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住密码"
android:layout_marginRight="30dp"
android:checked="true"
/>
<CheckBox
android:id="@+id/au_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="自动登陆"
android:layout_marginLeft="30dp"
/>
</LinearLayout> <android.support.v7.widget.AppCompatButton
android:id="@+id/btn_login"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login"/> <TextView android:id="@+id/link_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="No account yet? Create one"
android:gravity="center"
android:textSize="16dip"/> </LinearLayout>
</ScrollView>

登陆界面

package com.zj.login;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; import com.zj.cafetriafood.R; import butterknife.Bind;
import butterknife.ButterKnife; /**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
private SharedPreferences sp; @Bind(R.id.input_email) EditText _emailText;
@Bind(R.id.input_password) EditText _passwordText;
@Bind(R.id.btn_login) Button _loginButton;
@Bind(R.id.link_signup) TextView _signupLink;
@Bind(R.id.rm_pass) CheckBox _rmpass;
@Bind(R.id.au_login) CheckBox _aulogin;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
sp = this.getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
_loginButton.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
login();
}
}); _signupLink.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
// Start the Signup activity
Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
}
}); if(sp.getBoolean("ISCHECK", false))
{
_rmpass.setChecked(true); _emailText.setText(sp.getString("USER_NAME", ""));
_passwordText.setText(sp.getString("PASSWORD", "")); if(sp.getBoolean("AUTO_ISCHECK", false))
{
//设置默认是自动登录状态
_aulogin.setChecked(true);
//跳转界面
//Intent intent = new Intent(LoginActivity.this,MainActivity.class);
//startActivity(intent);
this.finish(); }
} } public void login() {
Log.d(TAG, "Login"); if (!validate()) {
onLoginFailed();
return;
} _loginButton.setEnabled(false); final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show(); String email = _emailText.getText().toString();
String password = _passwordText.getText().toString(); // TODO: Implement your own authentication logic here.
Log.i("test","email+password="+email+","+password); if(!email.equals("123")||!password.equals("123456"))
{
progressDialog.dismiss();
_loginButton.setEnabled(true);
_emailText.setText("");
_passwordText.setText("");
Toast.makeText(getApplication(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
return;
} if(_rmpass.isChecked())
{
//记住用户名、密码、
SharedPreferences.Editor editor = sp.edit();
editor.putString("USER_NAME", email);
editor.putString("PASSWORD", password); editor.commit(); sp.edit().putBoolean("ISCHECK", true).commit(); }else
{
sp.edit().putBoolean("ISCHECK", true).commit();
} if (_aulogin.isChecked())
{
sp.edit().putBoolean("AUTO_ISCHECK", true).commit();
}else
{
sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
} new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) { // TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
} @Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
} public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
} public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show(); _loginButton.setEnabled(true);
} public boolean validate() {
boolean valid = true; String email = _emailText.getText().toString();
String password = _passwordText.getText().toString(); if (email.isEmpty() || !Patterns.PHONE.matcher(email).matches()) {
_emailText.setError("enter a valid phone number");
valid = false;
} else {
_emailText.setError(null);
} if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
} return valid;
}
}

MainActivity

package com.zj.cafetriafood;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView; import com.zj.application.MyApplication;
import com.zj.login.LoginActivity; import butterknife.Bind;
import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { private SharedPreferences sp;
private MyApplication myApplication; @Bind(R.id.text_user) TextView text_user; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
sp = this.getSharedPreferences("userInfo", Activity.MODE_PRIVATE); if(sp.getBoolean("AUTO_ISCHECK", false))
{
myApplication= (MyApplication) getApplication();
myApplication.setUsername(sp.getString("USER_NAME",""));
}else
{
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
} text_user.setText(myApplication.getUsername()); } }

MyApplication

package com.zj.application;

import android.app.Application;

/**
* Created by jjx on 2016/5/22.
*/
public class MyApplication extends Application{ public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} String username; @Override
public void onCreate() {
super.onCreate();
setUsername("用户名");
}
}

参考链接

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

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

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

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

效果如下

Android之记住密码与自动登陆实现的更多相关文章

  1. android记住密码和自动登陆

    import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences ...

  2. php实现记住密码下次自动登陆

    这篇博客里面还写到 实现“记住我的登录状态”的功能方法,简言之,就是对首先对session进行用户信息赋值,检测session,失效后,利用cookie对其赋值: 在实现过程中,根据网上一些代码贴,整 ...

  3. 一个简单WPF登陆界面,包含记住密码,自动登录等功能,简洁美观

    简介:这是一个自己以前用WPF设计的登陆界面,属于一个实验性的界面窗体,如果用于产品还很有不足.但也是有一点学习价值.后台代码略有复杂,但基本上都有注释 分类,略有代码经验的一般都能看懂. 登陆界面外 ...

  4. Android 记住密码和自动登录界面的实现(SharedPreferences 的用法)

    原文:http://blog.csdn.net/liuyiming_/article/details/7704923 SharedPreferences介绍: SharedPreferences是An ...

  5. 基于localStorge开发登录模块的记住密码与自动登录

    前沿||我是乐于分享,善于交流的鸟窝 先做写一篇关于登录模块中记住密码与自动登录的模块.鸟窝微信:jkxx123321 关于这个模块功能模块的由来,这是鸟大大的处女秀,为什么这么说呢?一天在群里,一个 ...

  6. php中实现记住密码下次自动登录的例子

    这篇文章主要介绍了php中实现记住密码下次自动登录的例子,本文使用cookie实现记住密码和自动登录功能,需要的朋友可以参考下 做网站的时候经常会碰到要实现记住密码,下次自动登录,一周内免登陆,一个月 ...

  7. WinForm应用程序的开机自启、记住密码,自动登录的实现

    一.思路: 1.开机自启,自然是需要用到注册表,我们需要把程序添加到电脑的注册表中去 2.记住密码,自动登录,开机自启,在页面的呈现我们都使用复选框按钮来呈现 3.数据持久化,不能是数据库,可以是sq ...

  8. Cookie实现记住密码、自动登录

    前端代码 <form id="form" action="xxx" method="post"> <div> < ...

  9. 让 Putty 保存密码,自动登陆的四种方法

    Putty 基本是我在紧急时候用来登陆 Linux/Unix 终端的不二之先,因其小,开源,界面也非常实用.可是当你要在私有的机器上,经常性的要登陆很多机器的时候就觉得烦琐了,不光打开一堆的窗口,还要 ...

随机推荐

  1. javaIO(二)

    在程序中所有的数据都是以流的方式进行传输或保存的,程序需要数据时要使用输入流读取数据,而当程序需要将一些数据保存起来时,就要使用输出流. 在java.io包中流的操作主要有字节流.字符流两大类,两类都 ...

  2. Jquery+Ajax+Json的使用(微信答题实例)

    —————————————————————TP框架下的方法————————————————————————

  3. U盘中的autorun.inf

    怎么删除u盘里的autorun.inf 如果U盘中毒,刚插进机子时按住SHIFT五秒,这样就可以跳过预读,这样防止了预读时把病毒感染到机子上,在U盘盘符上点右键,看看有没有“Auto”选项: 1.如果 ...

  4. Python socket编程之四:模拟分时图

    建立 socket,先运行服务器,再运行客户端,建立连接后服务器从本地数据库调数据一截一截地发送给客户端,客户端接受数据绘图模拟分时图 1.socket # -*- coding: utf-8 -*- ...

  5. 如果你也和我一样,OSX反应慢,不妨试试这个

  6. 修改shell 将当前shell(默认是bash B SHELL )改为csh C SHELL

     在修改当前shell时,用命令: usermod -s  /bin/csh   home     home 为 你所想要改变的用户地址     此处home 为家目录,一般自己创建的用户都会在家目录 ...

  7. js中的getAttribute方法使用示例

    getAttribute()方法是一个函数.它只有一个参数——你打算查询的属性的名字,下面为大家介绍下其具体的使用   getAttribute()方法 至此,我们已经向大家介绍了两种检索特定元素节点 ...

  8. 如何用火车头采集当前页面url网址

    首先创建一个标签为本文网址,勾选后面的“从网址中采集”. 选择下面的“正则提取”,点击通配符“(?<content>?)”,这样在窗口中就显示为(?<content>[\s\S ...

  9. 1009: josephus问题

    1009: josephus问题 Time Limit: 1 Sec  Memory Limit: 64 MBSubmit: 549  Solved: 227 Description josephus ...

  10. hibernate中的session缓存

    1.什么是session缓存? 在 Session 接口的实现中包含一系列的 Java 集合, 这些 Java 集合构成了 Session 缓存. 只要 Session 实例没有结束生命周期, 且没有 ...