1. 程式人生 > >Android 記住密碼和自動登入介面的實現(SharedPreferences 的用法)

Android 記住密碼和自動登入介面的實現(SharedPreferences 的用法)

SharedPreferences介紹:

SharedPreferences是Android平臺上一個輕量級的儲存類,主要是儲存一些常用的配置引數,它是採用xml檔案存放資料的,檔案存放在"/data/data<package name>/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資料能被其他應用程式讀寫

結果截圖:




工程目錄:

Java程式碼

LoginActivity.java

<span style="font-family:'Courier New';">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();
			}
		});

	}
}</span>

LogoActivity.java
<span style="font-family:'Courier New';">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();

			}
		});

	}

}
</span>

WelcomeActivity.java
<span style="font-family:'Courier New';"><span style="BACKGROUND-COLOR: rgb(240,240,240); WHITE-SPACE: pre">package com.liu.activity;</span>
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);
	}

}</span>

佈局檔案:

login.xml檔案

<span style="font-family:'Courier New';"><?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:background="@drawable/logo_bg"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <ImageButton 
            android:id="@+id/img_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:background="@drawable/quit"/>

        <TextView
            android:id="@+id/tv_zh"
            android:layout_width="wrap_content"
            android:layout_height="35dip"
            android:layout_marginLeft="12dip"
            android:layout_marginTop="10dip"
            android:gravity="bottom"
            android:text="帳號:"
            android:textColor="#000000"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/et_zh"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:layout_below="@id/tv_zh"
            android:layout_marginLeft="12dip"
            android:layout_marginRight="10dip" />

        <TextView
            android:id="@+id/tv_mima"
            android:layout_width="wrap_content"
            android:layout_height="35dip"
            android:layout_below="@id/et_zh"
            android:layout_marginLeft="12dip"
            android:layout_marginTop="10dip"
            android:gravity="bottom"
            android:text="密碼:"
            android:textColor="#000000"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/et_mima"
            android:layout_width="fill_parent"
            android:layout_height="40dip"
            android:layout_below="@id/tv_mima"
            android:layout_marginLeft="12dip"
            android:layout_marginRight="10dip"
            android:maxLines="200"
            android:password="true"
            android:scrollHorizontally="true" />

        <CheckBox
            android:id="@+id/cb_mima"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/et_mima"
            android:layout_marginLeft="12dip"
            android:text="記住密碼"
            android:textColor="#000000" />

        <CheckBox
            android:id="@+id/cb_auto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/cb_mima"
            android:layout_marginLeft="12dip"
            android:text="自動登入"
            android:textColor="#000000" />
        <Button
            android:id="@+id/btn_login"
            android:layout_width="80dip"
            android:layout_height="40dip"
            android:layout_below="@id/et_mima"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@id/cb_auto"
            android:layout_marginRight="10dip"
            android:gravity="center"
            android:text="登入"
            android:textColor="#000000"
            android:textSize="18sp"/>

        
    </RelativeLayout>
    
    

</LinearLayout></span>

logo.xml檔案

<span style="font-family:'Courier New';"><?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:background="@drawable/logo_bg"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:layout_weight="3">

        <ProgressBar
            android:id="@+id/pgBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true" />

        <TextView
            android:id="@+id/tv1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/pgBar"
            android:layout_centerHorizontal="true"
            android:text="正在登入..."
            android:textColor="#000000"
            android:textSize="18sp" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >

        <Button
            android:id="@+id/btn_back"
            android:layout_width="70dip"
            android:layout_height="35dip"
            android:text="取消"
            android:textColor="#000000"
            android:textSize="12sp" />
    </LinearLayout>


</LinearLayout></span>

welcome.xml

<span style="font-family:'Courier New';"><?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:layout_gravity="center"
    android:background="@drawable/login_bg"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="登陸成功,進入使用者介面"
        android:textColor="#000000"
        android:textSize="20sp" />

</LinearLayout></span>