安卓008移动存储--SharePreference

来源:互联网 发布:宋喆职务侵占罪知乎 编辑:程序博客网 时间:2024/04/29 14:11



SharedPreferences

   SharedPreferences,是一个非常轻量的数据存储方式,
   以xml的形式存取简单的键值对数据,
   数据类型包括(ints,floats,boolean,strings,longs,Set<String>(android 11以后)),
   存放位置:/data/data/<包名>/shared_prefs,存放的是应用私有的数据,
   主要用于软件偏好设置,简单信息存取等
  
   1. 如何取得SharedPreferences对象

     - Context.getSharedPreferences(name,mode)
       1. 作用,打开以name命名的 xml文件,通过SharedPreferences来访问实现存储
       2. name :xml 文件名,注意不要扩展名,默认是 name.xml(user.xml)
       3. mode :文件操作类型  : 一般设置 默认的: mode_private  
          在android 4.0 以后,只支持私有的模式


     - Activity.getPreferences(mode)
       1. 作用:访问以当前Activity类名命名的xml文件


   2. get values
      - SharedPreferences.getString(key,defaltValue)//取 字符串类型的值对数据 defaltValue:null
      - SharedPreferences.getInt(key,defaltValue)//取 字符串类型的值对数据 defaltValue:0
      - SharedPreferences.getBoolean(key,defaltValue)//取 字符串类型的值对数据 defaltValue:false


   3. save values  
         取得编辑器
       Editor editor=SharedPreferences.edit();
        editor.putString(key,value)
editor.putInt(key,value)
editor.putBoolean(key,value)


       editor.commit();//提交 ,把编辑器的内容更新到SharedPreferences关联的xml文件中
     


  案例 :运用SharedPreferences保存用户登录信息
    要求:
    1.账号密码验证成功,则进入另一个Activity:SystemActivity
    2.选中复选框,则用户登录时,把账户及密码信息以SharedPreferences存储xml数据
    3.应用下次启动,依据存储的复选框状态值,决定是否填充账户与密码信息
    4.对存入SharedPreference的值对信息加密
       对称加密: des 、aes
       非对称加密: RSA
        100多M的文档 通过md5生成 32位16进制数 摘要
       摘要: md5 、sha1:
       
       种子  seed




activity_login.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_login"
    tools:context=".LoginActivity" >


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
        android:src="@drawable/ic_logo" />


    <EditText
        android:id="@+id/account_edt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:paddingLeft="45dp"
        android:ems="10" >
        <requestFocus />
    </EditText>
    <!-- layout_alignBaseline:与某个控件基线对齐 ,与底部对齐不同 -->
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="账号:"
        android:layout_alignBaseline="@id/account_edt"
        android:layout_alignLeft="@id/account_edt"
        android:layout_marginLeft="6dp"
        />
  <!-- android:inputType="textPassword" -->
    <EditText
        android:id="@+id/pwd_edt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/account_edt"
        android:layout_below="@+id/account_edt"
        android:paddingLeft="45dp"
        android:layout_marginTop="20dp"
        
        android:ems="10" />
    
     <!-- layout_alignBaseline:与某个控件基线对齐 ,与底部对齐不同 -->
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="密码:"
        android:layout_alignBaseline="@id/pwd_edt"
        android:layout_alignLeft="@id/pwd_edt"
        android:layout_marginLeft="6dp"
        />
   <!-- android:button:复选按钮左边的图片 -->
    <CheckBox
        android:id="@+id/remenber_chx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/pwd_edt"
        android:layout_below="@+id/pwd_edt"
        android:layout_marginTop="22dp"
        android:button="@drawable/check_select"
       
        android:text="记住密码" />


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/remenber_chx"
        android:layout_marginTop="32dp"
        android:layout_toLeftOf="@+id/imageView1"
        android:onClick="login"
        
        android:background="@drawable/login_select"
       />


    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/imageView1"
        android:onClick="register"
        android:background="@drawable/register_select"
        />


</RelativeLayout>



选择器:drawable/1/2/3.xml

 

Login_select.xml

 

<?xml version="1.0"encoding="utf-8"?>

<selectorxmlns:android="http://schemas.android.com/apk/res/android" >

   <item android:state_pressed="true"android:drawable="@drawable/bt_login_dark"></item>

   <itemandroid:drawable="@drawable/bt_login"></item>

 

</selector>

 

 

Register_selector.xml

 

<?xml version="1.0"encoding="utf-8"?>

<selectorxmlns:android="http://schemas.android.com/apk/res/android" >

   <item android:state_pressed="true"android:drawable="@drawable/bt_login_dark"></item>

   <itemandroid:drawable="@drawable/bt_login"></item>

 

</selector>

 

Check_selector.xml

 

<?xml version="1.0"encoding="utf-8"?>

<selectorxmlns:android="http://schemas.android.com/apk/res/android" >

   <item android:state_checked="true"android:drawable="@drawable/license_check"></item>

   <itemandroid:drawable="@drawable/license_uncheck"></item>

 

</selector>

 

 

 

 

 

LoginActivity.java

 

package cn.itcast.sharedpreferences;

 

import cn.itcast.sharedpreferences.utils.AESEncryptor;

import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

importandroid.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.text.TextUtils;

import android.view.View;

import android.widget.CheckBox;

import android.widget.EditText;

import android.widget.Toast;

 

public class LoginActivity extends Activity{

         privatestatic final String SEED = "android1110";//加密种子

         privateEditText mAccountEdt;//账号编辑框

         privateEditText mPwdEdt;//密码编辑框

         privateCheckBox mRemenberChx;//复选框

         privateSharedPreferences sp;//SharedPreferences存储对象

         privateContext context;

 

         @Override

         protectedvoid onCreate(Bundle savedInstanceState) {

                  super.onCreate(savedInstanceState);

                   setContentView(R.layout.activity_login);

                   initView();

                   autoFillInfo();

         }

         //自动填充信息

         privatevoid autoFillInfo() {

                   if(sp.getBoolean("isChecked",false)){

                            //自动填充

                            mAccountEdt.setText(sp.getString("username",null));

                            try{

                                     //解密

                                     mPwdEdt.setText(AESEncryptor.decrypt(SEED,sp.getString("password", null)));

                            }catch (Exception e) {

                                     //TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                            mRemenberChx.setChecked(true);

                   }

                  

         }

         //初始化视图

         privatevoid initView() {

           context=this;

          mAccountEdt=(EditText)findViewById(R.id.account_edt);

           mPwdEdt=(EditText)findViewById(R.id.pwd_edt);

          mRemenberChx=(CheckBox)findViewById(R.id.remenber_chx);

           //取得SharedPreferences对象 ,访问info.xml文件

           sp=getSharedPreferences("info",Context.MODE_PRIVATE);

                  

         }

         //注册

         publicvoid register(View v){

                  

         }

         //登录

         publicvoid login(View v){

                   //取得账号和密码

                   Stringaccount=mAccountEdt.getText().toString().trim();

                   Stringpwd=mPwdEdt.getText().toString().trim();

                  //验证用户名密码是否合法: 只要不为空即合法

                   if(TextUtils.isEmpty(account)||TextUtils.isEmpty(pwd)){

                            Toast.makeText(context,"用户名或者密码为空", Toast.LENGTH_SHORT).show();

                            return;

                   }

                  

                   //用户名和密码不为空  1. 保存账号和密码信息   2. 跳转到SystemActivity界面

    //1. 保存账号和密码信息

                   remenberInfo(account,pwd);

                  

         //      2. 跳转到SystemActivity界面

                  

                   Intentintent=new Intent();

                   intent.setClass(context,SystemActivity.class);

                   startActivity(intent);

         }

        

         //保存账号和密码信息

         privatevoid remenberInfo(String account, String pwd) {

                   Editoreditor=sp.edit();//取得编辑器

                   if(mRemenberChx.isChecked()){

                            editor.putString("username",account);

                            try{

                                     //加密  :seed:加密的种子  clearText :清晰文本

                                     editor.putString("password",AESEncryptor.encrypt(SEED, pwd));

                            }catch (Exception e) {

 

                                     e.printStackTrace();

                            }

                            editor.putBoolean("isChecked",true);

                   }else{

                            editor.putBoolean("isChecked",false);

                   }

 

                   editor.commit();//提交

         }

 

}

 

 

 

 

 

SystemActivity.java

package cn.itcast.sharedpreferences;


import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;


public class SystemActivity extends Activity {
         @Override
         protectedvoid onCreate(Bundle savedInstanceState) {
                   //TODO Auto-generated method stub
                   super.onCreate(savedInstanceState);
                   ImageViewview=new ImageView(this);
                   view.setImageResource(R.drawable.pic6);
                   setContentView(view);
         }


}





AESEncryptor.java

package cn.itcast.sharedpreferences.utils;


import java.security.SecureRandom;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class AESEncryptor { 
    /**
     * AES加密
     */ 
    public static String encrypt(String seed, String cleartext)throws Exception {   
        byte[] rawKey = getRawKey(seed.getBytes());  
        byte[] result = encrypt(rawKey,cleartext.getBytes());   
        return toHex(result);   
    }   
    /**
     * AES解密
     */ 
    public static String decrypt(String seed, String encrypted)throws Exception {   
        byte[] rawKey = getRawKey(seed.getBytes());  
        byte[] enc = toByte(encrypted);   
        byte[] result = decrypt(rawKey, enc);   
        return new String(result);   
    }   
  
    private static byte[] getRawKey(byte[] seed) throws Exception {  
        KeyGenerator kgen =KeyGenerator.getInstance("AES");   
        // SHA1PRNG 强随机种子算法, 要区别4.2以上版本的调用方法  
        SecureRandom sr = null;  
      if (android.os.Build.VERSION.SDK_INT >=  17) { 
        sr = SecureRandom.getInstance("SHA1PRNG","Crypto");  
      } else {  
        sr =SecureRandom.getInstance("SHA1PRNG");  
      }   
        sr.setSeed(seed);   
        kgen.init(256, sr); // 192 and 256 bits may not beavailable   
        SecretKey skey = kgen.generateKey();   
        byte[] raw = skey.getEncoded();   
        return raw;   
       
    }   
  
       
    private static byte[] encrypt(byte[] raw, byte[] clear) throwsException {   
        SecretKeySpec skeySpec = new SecretKeySpec(raw,"AES");   
        Cipher cipher = Cipher.getInstance("AES");  
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);  
        byte[] encrypted = cipher.doFinal(clear);  
        return encrypted;   
    }   
  
    private static byte[] decrypt(byte[] raw, byte[] encrypted)throws Exception {   
        SecretKeySpec skeySpec = new SecretKeySpec(raw,"AES");   
        Cipher cipher =Cipher.getInstance("AES");   
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);  
        byte[] decrypted = cipher.doFinal(encrypted);  
        return decrypted;   
    }   
  
    public static String toHex(String txt) {   
        return toHex(txt.getBytes());   
    }   
    public static String fromHex(String hex) {   
        return new String(toByte(hex));   
    }   
       
    public static byte[] toByte(String hexString) {   
        int len = hexString.length()/2;   
        byte[] result = new byte[len];   
        for (int i = 0; i < len; i++)   
            result[i] =Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();   
        return result;   
    }   
  
    public static String toHex(byte[] buf) {   
        if (buf == null)   
            return "";   
        StringBuffer result = newStringBuffer(2*buf.length);   
        for (int i = 0; i < buf.length; i++) {  
            appendHex(result, buf[i]);  
        }   
        return result.toString();   
    }   
    private final static String HEX = "0123456789ABCDEF";  
    private static void appendHex(StringBuffer sb, byte b) {  
       sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));  
    }   

 












0 0