Jcheng一霸 发表于 2013-8-28 16:27

Android使用sharedpreference实现记住密码功能

1好久没写博客了,自从进入新公司以来学到了很多知识,博客是把自己学过的知识存储并方便以后查看的好工具,最近一直在研究4.0源码,以后更多的是深入研究源码,对于应用可能写的会很少,但是无论如何每天积累点,每天都学点,刚进公司老大让写一个记事本程序,要求能够登录,我在写的时候加入了记住密码和显示密码的功能,原本想加自动登录功能,但是还是两个选项比较合适,多了不多,直接上代码。(今天时间较紧,写的很仓促)package com.gionee.android.notepad.noteactivity;   import com.gionee.android.notepad.service.FileService;   import android.app.Activity;import android.app.AlertDialog;import android.app.AlertDialog.Builder;import android.content.DialogInterface;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.text.Editable;import android.text.InputType;import android.text.TextWatcher;import android.text.method.HideReturnsTransformationMethod;import android.text.method.PasswordTransformationMethod;import android.view.KeyEvent;import android.view.View;import android.view.View.OnClickListener;import android.widget.ArrayAdapter;import android.widget.AutoCompleteTextView;import android.widget.Button;import android.widget.CheckBox;import android.widget.EditText;import android.widget.Toast;   /**   * @author Ma Guohui   * @FileDescription:登陆Activity   * @version 2012-10-26 下午2:55:03   * @ChangeList:   */public class Gn_LoginActivity extends Activity {            private AutoCompleteTextView mUserNameAuto;      private EditText mPasswordEt;      private Button mLoginBt;      private Button mCancelBt;      private String mUserStr;      private String mPwdStr;      private CheckBox mRemPwdCb;      private CheckBox mShowpwdCb;      private SharedPreferences mPasswordSp;      private FileService fileService;       @Override   public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);          mUserNameAuto = (AutoCompleteTextView) findViewById(R.id.cardNumAuto);          mPasswordEt = (EditText) findViewById(R.id.editPwd);          mLoginBt = (Button) findViewById(R.id.button1);          mCancelBt = (Button) findViewById(R.id.button2);          mRemPwdCb = (CheckBox) findViewById(R.id.checkBox1);          mShowpwdCb = (CheckBox) findViewById(R.id.checkBox2);          fileService = new FileService(this);                  savePassword();                  mLoginBt.setOnClickListener(new OnClickListener() {//登陆按钮设置监听事件               public void onClick(View v) {                  // FileService fileService = new FileService(this);                  // TODO Auto-generated method stub                  // user = username.getText().toString();                  mUserStr = mUserNameAuto.getText().toString().trim();                  mPwdStr = mPasswordEt.getText().toString().trim();                   if (fileService.login(mUserStr, mPwdStr)) {//执行登录验证操作(fieService是另一个类的实例哦)                  if (mRemPwdCb.isChecked()) {//选择记住密码功能                        mPasswordSp.edit().putString(mUserStr, mPwdStr).commit();//记住密码,把密码信息放入SharedPreferences文件中                      }                      Intent intent = new Intent(Gn_LoginActivity.this,                              MainActivity.class);                      startActivity(intent);//跳转到其他显示界面                  Gn_LoginActivity.this.finish();                  } else {//提示密码错误                  Toast.makeText(Gn_LoginActivity.this, getResources().getString(R.string.password_error),                              Toast.LENGTH_SHORT).show();                  }            }         });          mCancelBt.setOnClickListener(new OnClickListener() {//取消事件监听               @Override             public void onClick(View v) {                  // TODO Auto-generated method stub                  dialog();//显示对话框            }          });          mShowpwdCb.setOnClickListener(new OnClickListener() {//显示密码事件操作            /*            * 明文显示密码 :               * 明文显示:android.text.method.HideReturnsTransformationMethod ;               * 密文显示:android.text.method.PasswordTransformationMethod ;               */             @Override             public void onClick(View v) {                  // TODO Auto-generated method stub                  if (mShowpwdCb.isChecked()) {// 被选中,则显示明文                      // 将文本框的内容设置成明文显示                      mPasswordEt.setTransformationMethod(HideReturnsTransformationMethod                              .getInstance());                  } else {                      // 将文本框内容设置成密文的方式显示                      mPasswordEt.setTransformationMethod(PasswordTransformationMethod                              .getInstance());                  }            }          });      }       @Override   public boolean onKeyDown(int keyCode, KeyEvent event) {//监听返回键事件          // TODO Auto-generated method stub          if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {            dialog();          }          return false;      }       private void dialog() {//显示对话框方法(退出时哦)      AlertDialog.Builder builder = new Builder(Gn_LoginActivity.this);          builder.setMessage(this.getResources().getString(R.string.isLogout));          builder.setTitle(this.getResources().getString(R.string.logoutPrompt));          builder.setPositiveButton(this.getResources().getString(R.string.logout_yes), new DialogInterface.OnClickListener() {               @Override             public void onClick(DialogInterface dialog, int which) {                  // TODO Auto-generated method stub                  dialog.dismiss();                  Gn_LoginActivity.this.finish();            }         });          builder.setNegativeButton(this.getResources().getString(R.string.logout_no), new DialogInterface.OnClickListener() {               @Override             public void onClick(DialogInterface dialog, int which) {                  dialog.dismiss();            }          });          builder.create().show();      }       private void savePassword() {//保存密码方法,数据放入SharedPreferences文件          /*          * 参数简述:         * Name—获得SharedPreferences之后,将会在应用程序的私有文件夹中保存着一个XML文件,第一个参数name就是这个文件名字         * 。 Mode—XML文件的保存模式,默认为0,也就是MODE_PRIVATE         */         mPasswordSp = this.getSharedPreferences("passwordFile", MODE_PRIVATE);          mRemPwdCb.setChecked(true);// 默认为记住密码          mUserNameAuto.setThreshold(1);// 输入1个字母就开始自动提示          // 隐藏密码为InputType.TYPE_TEXT_VARIATION_PASSWORD,也就是0x81          // 显示密码为InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD,也就是0x91          mPasswordEt.setInputType(InputType.TYPE_CLASS_TEXT                  | InputType.TYPE_TEXT_VARIATION_PASSWORD);          mUserNameAuto.addTextChangedListener(new TextWatcher() {               @Override             public void onTextChanged(CharSequence s, int start, int before,                      int count) {                  // TODO Auto-generated method stub                  String[] allUserName = new String;// sp.getAll().size()返回的是有多少个键值对                  allUserName = mPasswordSp.getAll().keySet().toArray(new String);                  ArrayAdapter<String> adapter = new ArrayAdapter<String>(                        Gn_LoginActivity.this,                        android.R.layout.simple_dropdown_item_1line,                        allUserName);                  mUserNameAuto.setAdapter(adapter);// 设置数据适配器            }               @Override             public void beforeTextChanged(CharSequence s, int start, int count,                      int after) {                  // TODO Auto-generated method stub               }               @Override             public void afterTextChanged(Editable s) {                  // TODO Auto-generated method stub                  // 自动输入密码                  mPasswordEt.setText(mPasswordSp.getString(mUserNameAuto.getText().toString(),                        ""));               }          });      }}   
布局文件内容   
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   android:layout_width="fill_parent"   android:layout_height="fill_parent"   android:orientation="vertical" >      <TextView         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="@string/username" />   <AutoCompleteTextView         android:id="@+id/cardNumAuto"         android:layout_width="fill_parent"         android:layout_height="wrap_content" >      </AutoCompleteTextView>                  <TextView         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="@string/password" />   <EditText         android:id="@+id/editPwd"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:ems="10"         android:inputType="textPassword" >          <requestFocus />   </EditText>            <LinearLayout android:id="@+id/LinearLayout01"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:gravity="center">          <CheckBox         android:id="@+id/checkBox1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="@string/rempwd" />          <CheckBox         android:id="@+id/checkBox2"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="@string/showpwd" />            </LinearLayout>   <LinearLayout android:id="@+id/LinearLayout01"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:gravity="center">          <Button         android:id="@+id/button1"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="登陆" />      <Button         android:id="@+id/button2"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="取消" />            </LinearLayout> </LinearLayout>   
运行效果图(没图说个JB)   
   
http://www.apkbus.com/data/attachment/forum/201301/31/170403c7peerh3vvmpr7t7.jpg      
http://www.apkbus.com/data/attachment/forum/201301/31/170404tei9ffswi62s5sz6.jpg      
http://www.apkbus.com/data/attachment/forum/201301/31/170404dpsyps5o1zgjztzy.jpg   
页: [1]
查看完整版本: Android使用sharedpreference实现记住密码功能