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

原文:http://blog.csdn.net/liuyiming_/article/details/7704923

SharedPreferences介绍:

SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置参数,它是采用xml文件存放数据的,文件存放在”/data/data/shared_prefs”目录下。

SharedPreferences的用法:

由于SharedPreferences是一个接口,而且在这个接口里没有提供写入数据和读取数据的能力。但它是通过其Editor接口中的一些方法来操作SharedPreference的,用法见下面代码:

Context.getSharedPreferences(String name,int mode)来得到一个SharedPreferences实例

name:是指文件名称,不需要加后缀.xml,系统会自动为我们添加上

mode:是指定读写方式,其值有三种,分别为:

Context.MODE_PRIVATE:指定该SharedPreferences数据只能被本应用程序读、写

Context.MODE_WORLD_READABLE指定该SharedPreferences数据能被其他应用程序读,但不能写

Context.MODE_WORLD_WRITEABLE指定该SharedPreferences数据能被其他应用程序读写


结果截图:

Android 记住密码和自动登录界面的实现(SharedPreferences 的用法)_第1张图片


Android 记住密码和自动登录界面的实现(SharedPreferences 的用法)_第2张图片


Android 记住密码和自动登录界面的实现(SharedPreferences 的用法)_第3张图片


工程目录:

Android 记住密码和自动登录界面的实现(SharedPreferences 的用法)_第4张图片


Java代码

LoginActivity.java

[java] view plain copy
print ?
  1. “font-family:’Courier New’;”>package com.liu.activity;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.backup.SharedPreferencesBackupHelper;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.SharedPreferences;  
  8. import android.content.SharedPreferences.Editor;  
  9. import android.os.Bundle;  
  10. import android.text.Spannable;  
  11. import android.view.View;  
  12. import android.view.View.OnClickListener;  
  13. import android.view.Window;  
  14. import android.widget.Button;  
  15. import android.widget.CheckBox;  
  16. import android.widget.CompoundButton;  
  17. import android.widget.CompoundButton.OnCheckedChangeListener;  
  18. import android.widget.EditText;  
  19. import android.widget.ImageButton;  
  20. import android.widget.Toast;  
  21.   
  22. public class LoginActivity extends Activity {  
  23.       
  24.     private EditText userName, password;  
  25.     private CheckBox rem_pw, auto_login;  
  26.     private Button btn_login;  
  27.     private ImageButton btnQuit;  
  28.     private String userNameValue,passwordValue;  
  29.     private SharedPreferences sp;  
  30.   
  31.     public void onCreate(Bundle savedInstanceState) {  
  32.         super.onCreate(savedInstanceState);  
  33.           
  34.         //去除标题  
  35.         this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  36.         setContentView(R.layout.login);  
  37.           
  38.         //获得实例对象  
  39.         sp = this.getSharedPreferences(“userInfo”, Context.MODE_WORLD_READABLE);  
  40.         userName = (EditText) findViewById(R.id.et_zh);  
  41.         password = (EditText) findViewById(R.id.et_mima);  
  42.         rem_pw = (CheckBox) findViewById(R.id.cb_mima);  
  43.         auto_login = (CheckBox) findViewById(R.id.cb_auto);  
  44.         btn_login = (Button) findViewById(R.id.btn_login);  
  45.         btnQuit = (ImageButton)findViewById(R.id.img_btn);  
  46.           
  47.           
  48.         //判断记住密码多选框的状态  
  49.       if(sp.getBoolean(“ISCHECK”false))  
  50.         {  
  51.           //设置默认是记录密码状态  
  52.           rem_pw.setChecked(true);  
  53.           userName.setText(sp.getString(”USER_NAME”“”));  
  54.           password.setText(sp.getString(”PASSWORD”“”));  
  55.           //判断自动登陆多选框状态  
  56.           if(sp.getBoolean(“AUTO_ISCHECK”false))  
  57.           {  
  58.                  //设置默认是自动登录状态  
  59.                  auto_login.setChecked(true);  
  60.                 //跳转界面  
  61.                 Intent intent = new Intent(LoginActivity.this,LogoActivity.class);  
  62.                 LoginActivity.this.startActivity(intent);  
  63.                   
  64.           }  
  65.         }  
  66.           
  67.         // 登录监听事件  现在默认为用户名为:liu 密码:123  
  68.         btn_login.setOnClickListener(new OnClickListener() {  
  69.   
  70.             public void onClick(View v) {  
  71.                 userNameValue = userName.getText().toString();  
  72.                 passwordValue = password.getText().toString();  
  73.                   
  74.                 if(userNameValue.equals(“liu”)&&passwordValue.equals(“123”))  
  75.                 {  
  76.                     Toast.makeText(LoginActivity.this,“登录成功”, Toast.LENGTH_SHORT).show();  
  77.                     //登录成功和记住密码框为选中状态才保存用户信息  
  78.                     if(rem_pw.isChecked())  
  79.                     {  
  80.                      //记住用户名、密码、  
  81.                       Editor editor = sp.edit();  
  82.                       editor.putString(”USER_NAME”, userNameValue);  
  83.                       editor.putString(”PASSWORD”,passwordValue);  
  84.                       editor.commit();  
  85.                     }  
  86.                     //跳转界面  
  87.                     Intent intent = new Intent(LoginActivity.this,LogoActivity.class);  
  88.                     LoginActivity.this.startActivity(intent);  
  89.                     //finish();  
  90.                       
  91.                 }else{  
  92.                       
  93.                     Toast.makeText(LoginActivity.this,“用户名或密码错误,请重新登录”, Toast.LENGTH_LONG).show();  
  94.                 }  
  95.                   
  96.             }  
  97.         });  
  98.   
  99.         //监听记住密码多选框按钮事件  
  100.         rem_pw.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  101.             public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {  
  102.                 if (rem_pw.isChecked()) {  
  103.                       
  104.                     System.out.println(”记住密码已选中”);  
  105.                     sp.edit().putBoolean(”ISCHECK”true).commit();  
  106.                       
  107.                 }else {  
  108.                       
  109.                     System.out.println(”记住密码没有选中”);  
  110.                     sp.edit().putBoolean(”ISCHECK”false).commit();  
  111.                       
  112.                 }  
  113.   
  114.             }  
  115.         });  
  116.           
  117.         //监听自动登录多选框事件  
  118.         auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {  
  119.             public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {  
  120.                 if (auto_login.isChecked()) {  
  121.                     System.out.println(”自动登录已选中”);  
  122.                     sp.edit().putBoolean(”AUTO_ISCHECK”true).commit();  
  123.   
  124.                 } else {  
  125.                     System.out.println(”自动登录没有选中”);  
  126.                     sp.edit().putBoolean(”AUTO_ISCHECK”false).commit();  
  127.                 }  
  128.             }  
  129.         });  
  130.           
  131.         btnQuit.setOnClickListener(new OnClickListener() {  
  132.               
  133.             @Override  
  134.             public void onClick(View v) {  
  135.                 finish();  
  136.             }  
  137.         });  
  138.   
  139.     }  
  140. }  
package com.liu.activity;

import android.app.Activity;
import android.app.backup.SharedPreferencesBackupHelper;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Spannable;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class LoginActivity extends Activity {

    private EditText userName, password;
    private CheckBox rem_pw, auto_login;
    private Button btn_login;
    private ImageButton btnQuit;
    private String userNameValue,passwordValue;
    private SharedPreferences sp;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //去除标题
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);

        //获得实例对象
        sp = this.getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE);
        userName = (EditText) findViewById(R.id.et_zh);
        password = (EditText) findViewById(R.id.et_mima);
        rem_pw = (CheckBox) findViewById(R.id.cb_mima);
        auto_login = (CheckBox) findViewById(R.id.cb_auto);
        btn_login = (Button) findViewById(R.id.btn_login);
        btnQuit = (ImageButton)findViewById(R.id.img_btn);


        //判断记住密码多选框的状态
      if(sp.getBoolean("ISCHECK", false))
        {
          //设置默认是记录密码状态
          rem_pw.setChecked(true);
          userName.setText(sp.getString("USER_NAME", ""));
          password.setText(sp.getString("PASSWORD", ""));
          //判断自动登陆多选框状态
          if(sp.getBoolean("AUTO_ISCHECK", false))
          {
                 //设置默认是自动登录状态
                 auto_login.setChecked(true);
                //跳转界面
                Intent intent = new Intent(LoginActivity.this,LogoActivity.class);
                LoginActivity.this.startActivity(intent);

          }
        }

        // 登录监听事件  现在默认为用户名为:liu 密码:123
        btn_login.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                userNameValue = userName.getText().toString();
                passwordValue = password.getText().toString();

                if(userNameValue.equals("liu")&&passwordValue.equals("123"))
                {
                    Toast.makeText(LoginActivity.this,"登录成功", Toast.LENGTH_SHORT).show();
                    //登录成功和记住密码框为选中状态才保存用户信息
                    if(rem_pw.isChecked())
                    {
                     //记住用户名、密码、
                      Editor editor = sp.edit();
                      editor.putString("USER_NAME", userNameValue);
                      editor.putString("PASSWORD",passwordValue);
                      editor.commit();
                    }
                    //跳转界面
                    Intent intent = new Intent(LoginActivity.this,LogoActivity.class);
                    LoginActivity.this.startActivity(intent);
                    //finish();

                }else{

                    Toast.makeText(LoginActivity.this,"用户名或密码错误,请重新登录", Toast.LENGTH_LONG).show();
                }

            }
        });

        //监听记住密码多选框按钮事件
        rem_pw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if (rem_pw.isChecked()) {

                    System.out.println("记住密码已选中");
                    sp.edit().putBoolean("ISCHECK", true).commit();

                }else {

                    System.out.println("记住密码没有选中");
                    sp.edit().putBoolean("ISCHECK", false).commit();

                }

            }
        });

        //监听自动登录多选框事件
        auto_login.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if (auto_login.isChecked()) {
                    System.out.println("自动登录已选中");
                    sp.edit().putBoolean("AUTO_ISCHECK", true).commit();

                } else {
                    System.out.println("自动登录没有选中");
                    sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
                }
            }
        });

        btnQuit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
}


LogoActivity.java

[java] view plain copy
print ?
  1. “font-family:’Courier New’;”>package com.liu.activity;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.content.SharedPreferences;  
  6. import android.content.SharedPreferences.Editor;  
  7. import android.opengl.ETC1;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.view.Window;  
  12. import android.view.animation.AlphaAnimation;  
  13. import android.view.animation.Animation;  
  14. import android.view.animation.Animation.AnimationListener;  
  15. import android.widget.Button;  
  16. import android.widget.ImageButton;  
  17. import android.widget.ImageView;  
  18. import android.widget.ProgressBar;  
  19.   
  20. public class LogoActivity extends Activity {  
  21.     private ProgressBar progressBar;  
  22.     private Button backButton;  
  23.   
  24.     protected void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         // 去除标题  
  27.         this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  28.         setContentView(R.layout.logo);  
  29.   
  30.         progressBar = (ProgressBar) findViewById(R.id.pgBar);  
  31.         backButton = (Button) findViewById(R.id.btn_back);  
  32.   
  33.         Intent intent = new Intent(this, WelcomeAvtivity.class);  
  34.         LogoActivity.this.startActivity(intent);  
  35.   
  36.         backButton.setOnClickListener(new OnClickListener() {  
  37.   
  38.             @Override  
  39.             public void onClick(View v) {  
  40.                 finish();  
  41.   
  42.             }  
  43.         });  
  44.   
  45.     }  
  46.   
  47. }  
  48.   
package com.liu.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.opengl.ETC1;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class LogoActivity extends Activity {
    private ProgressBar progressBar;
    private Button backButton;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 去除标题
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.logo);

        progressBar = (ProgressBar) findViewById(R.id.pgBar);
        backButton = (Button) findViewById(R.id.btn_back);

        Intent intent = new Intent(this, WelcomeAvtivity.class);
        LogoActivity.this.startActivity(intent);

        backButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });

    }

}

WelcomeActivity.java

[java] view plain copy
print ?
  1. “font-family:’Courier New’;”>“BACKGROUND-COLOR: rgb(240,240,240); WHITE-SPACE: pre”>package com.liu.activity;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4.   
  5. public class WelcomeAvtivity extends Activity {  
  6.   
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         // TODO Auto-generated method stub  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.welcome);  
  12.     }  
  13.   
  14. }  
package com.liu.activity;
import android.app.Activity;
import android.os.Bundle;

public class WelcomeAvtivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
    }

}


布局文件:

login.xml文件

[html] view plain copy
print ?
  1. <span style=“font-family:’Courier New’;”>xml version=“1.0” encoding=“utf-8”?>  
  2. <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”  
  3.     android:layout_width=“fill_parent”  
  4.     android:layout_height=“fill_parent”  
  5.     android:background=“@drawable/logo_bg”  
  6.     android:orientation=“vertical” >  
  7.   
  8.     <RelativeLayout  
  9.         android:layout_width=“fill_parent”  
  10.         android:layout_height=“wrap_content” >  
  11.         <ImageButton   
  12.             android:id=“@+id/img_btn”  
  13.             android:layout_width=“wrap_content”  
  14.             android:layout_height=“wrap_content”  
  15.             android:layout_alignParentRight=“true”  
  16.             android:background=“@drawable/quit”/>  
  17.   
  18.         <TextView  
  19.             android:id=“@+id/tv_zh”  
  20.             android:layout_width=“wrap_content”  
  21.             android:layout_height=“35dip”  
  22.             android:layout_marginLeft=“12dip”  
  23.             android:layout_marginTop=“10dip”  
  24.             android:gravity=“bottom”  
  25.             android:text=“帐号:”  
  26.             android:textColor=“#000000”  
  27.             android:textSize=“18sp” />  
  28.   
  29.         <EditText  
  30.             android:id=“@+id/et_zh”  
  31.             android:layout_width=“fill_parent”  
  32.             android:layout_height=“40dip”  
  33.             android:layout_below=“@id/tv_zh”  
  34.             android:layout_marginLeft=“12dip”  
  35.             android:layout_marginRight=“10dip” />  
  36.   
  37.         <TextView  
  38.             android:id=“@+id/tv_mima”  
  39.             android:layout_width=“wrap_content”  
  40.             android:layout_height=“35dip”  
  41.             android:layout_below=“@id/et_zh”  
  42.             android:layout_marginLeft=“12dip”  
  43.             android:layout_marginTop=“10dip”  
  44.             android:gravity=“bottom”  
  45.             android:text=“密码:”  
  46.             android:textColor=“#000000”  
  47.             android:textSize=“18sp” />  
  48.   
  49.         <EditText  
  50.             android:id=“@+id/et_mima”  
  51.             android:layout_width=“fill_parent”  
  52.             android:layout_height=“40dip”  
  53.             android:layout_below=“@id/tv_mima”  
  54.             android:layout_marginLeft=“12dip”  
  55.             android:layout_marginRight=“10dip”  
  56.             android:maxLines=“200”  
  57.             android:password=“true”  
  58.             android:scrollHorizontally=“true” />  
  59.   
  60.         <CheckBox  
  61.             android:id=“@+id/cb_mima”  
  62.             android:layout_width=“wrap_content”  
  63.             android:layout_height=“wrap_content”  
  64.             android:layout_below=“@id/et_mima”  
  65.             android:layout_marginLeft=“12dip”  
  66.             android:text=“记住密码”  
  67.             android:textColor=“#000000” />  
  68.   
  69.         <CheckBox  
  70.             android:id=“@+id/cb_auto”  
  71.             android:layout_width=“wrap_content”  
  72.             android:layout_height=“wrap_content”  
  73.             android:layout_below=“@id/cb_mima”  
  74.             android:layout_marginLeft=“12dip”  
  75.             android:text=“自动登录”  
  76.             android:textColor=“#000000” />  
  77.         <Button  
  78.             android:id=“@+id/btn_login”  
  79.             android:layout_width=“80dip”  
  80.             android:layout_height=“40dip”  
  81.             android:layout_below=“@id/et_mima”  
  82.             android:layout_alignParentRight=“true”  
  83.             android:layout_alignTop=“@id/cb_auto”  
  84.             android:layout_marginRight=“10dip”  
  85.             android:gravity=“center”  
  86.             android:text=“登录”  
  87.             android:textColor=“#000000”  
  88.             android:textSize=“18sp”/>  
  89.   
  90.           
  91.     RelativeLayout>  
  92.       
  93.       
  94.   
  95. LinearLayout>span>  



    
        

        

        

        

        

        

        
        


logo.xml文件

[html] view plain copy
print ?
  1. <span style=“font-family:’Courier New’;”>xml version=“1.0” encoding=“utf-8”?>  
  2. <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”  
  3.     android:layout_width=“fill_parent”  
  4.     android:layout_height=“fill_parent”  
  5.     android:background=“@drawable/logo_bg”  
  6.     android:orientation=“vertical” >  
  7.   
  8.     <RelativeLayout  
  9.         android:layout_width=“fill_parent”  
  10.         android:layout_height=“wrap_content”   
  11.         android:layout_weight=“3”>  
  12.   
  13.         <ProgressBar  
  14.             android:id=“@+id/pgBar”  
  15.             android:layout_width=“wrap_content”  
  16.             android:layout_height=“wrap_content”  
  17.             android:layout_centerInParent=“true” />  
  18.   
  19.         <TextView  
  20.             android:id=“@+id/tv1”  
  21.             android:layout_width=“wrap_content”  
  22.             android:layout_height=“wrap_content”  
  23.             android:layout_below=“@id/pgBar”  
  24.             android:layout_centerHorizontal=“true”  
  25.             android:text=“正在登录…”  
  26.             android:textColor=“#000000”  
  27.             android:textSize=“18sp” />  
  28.     RelativeLayout>  
  29.   
  30.     <LinearLayout  
  31.         android:layout_width=“fill_parent”  
  32.         android:layout_height=“wrap_content”  
  33.         android:layout_weight=“1”  
  34.         android:gravity=“center”  
  35.         android:orientation=“vertical” >  
  36.   
  37.         <Button  
  38.             android:id=“@+id/btn_back”  
  39.             android:layout_width=“70dip”  
  40.             android:layout_height=“35dip”  
  41.             android:text=“取消”  
  42.             android:textColor=“#000000”  
  43.             android:textSize=“12sp” />  
  44.     LinearLayout>  
  45.   
  46.   
  47. LinearLayout>span>  



    

        

        
    

    

        

welcome.xml

[html] view plain copy
print ?
  1. <span style=“font-family:’Courier New’;”>xml version=“1.0” encoding=“utf-8”?>  
  2. <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”  
  3.     android:layout_width=“fill_parent”  
  4.     android:layout_height=“fill_parent”  
  5.     android:layout_gravity=“center”  
  6.     android:background=“@drawable/login_bg”  
  7.     android:orientation=“vertical” >  
  8.   
  9.     <TextView  
  10.         android:layout_width=“fill_parent”  
  11.         android:layout_height=“wrap_content”  
  12.         android:gravity=“center”  
  13.         android:text=“登陆成功,进入用户界面”  
  14.         android:textColor=“#000000”  
  15.         android:textSize=“20sp” />  
  16.   
  17. LinearLayout>span>  



    




工程下载连接: 点击打开链接


你可能感兴趣的:(Android)