<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 6.2 數據存儲與訪問之——SharedPreferences保存用戶偏好參數 ## 本節引言: > 本節給大家介紹的是第二種存儲用戶數據的方式,使用SharedPreferences(保存用戶偏好參數)保存數據, 當我們的應用想要保存用戶的一些偏好參數,比如是否自動登陸,是否記住賬號密碼,是否在Wifi下才能 聯網等相關信息,如果使用數據庫的話,顯得有點大材小用了!我們把上面這些配置信息稱為用戶的偏好 設置,就是用戶偏好的設置,而這些配置信息通常是保存在特定的文件中!比如windows使用ini文件, 而J2SE中使用properties屬性文件與xml文件來保存軟件的配置信息;而在Android中我們通常使用 一個輕量級的存儲類——SharedPreferences來保存用戶偏好的參數!SharedPreferences也是使用xml文件, 然后類似于Map集合,使用鍵-值的形式來存儲數據;我們只需要調用SharedPreferences的getXxx(name), 就可以根據鍵獲得對應的值!使用起來很方便! ## 1.SharedPreferences使用示例: **使用流程圖**: ![](http://www.runoob.com/wp-content/uploads/2015/09/77015718.jpg) **實現代碼示例**: **運行效果圖**: 流程是輸入賬號密碼后點擊登錄,將信息保存到SharedPreference文件中, 然后重啟app,看到數據已經顯示在文本框中了 ![](http://www.runoob.com/wp-content/uploads/2015/09/56032594.jpg) 另外保存后,我們可以在File Expoler打開data/data/&lt;包名&gt;可以看到在shared_prefs目錄下 生成了一個xml文件(因為N5沒root,這里找了以前的效果圖): ![](http://www.runoob.com/wp-content/uploads/2015/09/51008434.jpg) 點擊導出到桌面可以看到里面的內容: ![](http://www.runoob.com/wp-content/uploads/2015/09/95851258.jpg) **代碼實現**: 布局文件**activity_main.xml**的編寫: ``` <LinearLayout 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:orientation="vertical" tools:context=".MyActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用戶登陸" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="請輸入用戶名" /> <EditText android:id="@+id/editname" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="用戶名" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="請輸入密碼" /> <EditText android:id="@+id/editpasswd" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="密碼" android:inputType="textPassword" /> <Button android:id="@+id/btnlogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="登錄" /> </LinearLayout> ``` 編寫簡單的SP工具類:**SharedHelper.java**: ``` /** * Created by Jay on 2015/9/2 0002. */ public class SharedHelper { private Context mContext; public SharedHelper() { } public SharedHelper(Context mContext) { this.mContext = mContext; } //定義一個保存數據的方法 public void save(String username, String passwd) { SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("username", username); editor.putString("passwd", passwd); editor.commit(); Toast.makeText(mContext, "信息已寫入SharedPreference中", Toast.LENGTH_SHORT).show(); } //定義一個讀取SP文件的方法 public Map<String, String> read() { Map<String, String> data = new HashMap<String, String>(); SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE); data.put("username", sp.getString("username", "")); data.put("passwd", sp.getString("passwd", "")); return data; } } ``` 最后是**MainActivity.java**實現相關邏輯: ``` public class MainActivity extends AppCompatActivity { private EditText editname; private EditText editpasswd; private Button btnlogin; private String strname; private String strpasswd; private SharedHelper sh; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = getApplicationContext(); sh = new SharedHelper(mContext); bindViews(); } private void bindViews() { editname = (EditText)findViewById(R.id.editname); editpasswd = (EditText)findViewById(R.id.editpasswd); btnlogin = (Button)findViewById(R.id.btnlogin); btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { strname = editname.getText().toString(); strpasswd = editpasswd.getText().toString(); sh.save(strname,strpasswd); } }); } @Override protected void onStart() { super.onStart(); Map<String,String> data = sh.read(); editname.setText(data.get("username")); editpasswd.setText(data.get("passwd")); } } ``` ## 2.讀取其他應用的SharedPreferences > **核心**: 獲得其他app的Context,而這個Context代表訪問該app的全局信息的接口,而決定應用的唯一標識 是應用的包名,所以我們可以通過應用包名獲得對應app的Context 另外有一點要注意的是:其他應用的SP文件是否能被讀寫的前提就是SP文件是否指定了可讀或者 可寫的權限,我們上面創建的是MODE_PRIVATE的就不可以了~所以說你像讀別人的SP里的數據, 很難,另外,一些關鍵的信息,比如密碼保存到SP里,一般都是會做加密的,所以只能自己寫自己玩~ 等下會講下常用的MD5加密方法! **實現流程圖**: ![](http://www.runoob.com/wp-content/uploads/2015/09/54316471.jpg) **代碼示例:** **運行效果圖**: ![](http://www.runoob.com/wp-content/uploads/2015/09/31896879.jpg) **代碼實現**: 我們讀取SP的操作放在MainActivity.java中完成,點擊按鈕后讀取SP,并通過Toast顯示出來: ``` public class MainActivity extends AppCompatActivity { private Context othercontext; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnshow = (Button) findViewById(R.id.btnshow); btnshow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //獲得第一個應用的包名,從而獲得對應的Context,需要對異常進行捕獲 try { othercontext = createPackageContext("com.jay.sharedpreferencedemo", Context.CONTEXT_IGNORE_SECURITY); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //根據Context取得對應的SharedPreferences sp = othercontext.getSharedPreferences("mysp", Context.MODE_WORLD_READABLE); String name = sp.getString("username", ""); String passwd = sp.getString("passwd", ""); Toast.makeText(getApplicationContext(), "Demo1的SharedPreference存的\n用戶名為:" + name + "\n密碼為:" + passwd, Toast.LENGTH_SHORT).show(); } }); } } ``` ## 3.使用MD5對SharedPreference的重要數據進行加密 > 嘿嘿,上面我們這樣直接把賬號密碼保存到sp里,如果沒root的手機,別的應用倒無法訪問手機, 如果root了,然后數據給其他應用獲取到,然后造成了一些后果,這...就不怪我們了,哈哈, 誰叫你root了~,這鍋我們不背,的確是這樣!但是作為一名有責任心的APP開發人員,我們總不能 這樣是吧,我們可以使用一些加密算法對用戶密碼進行加密,另外我們一般加密的都是用戶密碼! 下面我們簡畫個簡單的圖幫助大家理解下加密的處理的流程: ### 1.簡單的加密處理流程 **流程圖如下**: ![](http://www.runoob.com/wp-content/uploads/2015/09/86646661.jpg) **流程圖解析**: > * **Step 1**.用戶注冊賬號密碼,賬號密碼校驗后(賬號是否重復,密碼位數 &gt; 6位等), 即賬號密碼有效,注冊成功后,我們提交給服務器的賬號,以及本地加密過的密碼! > * **Step 2**.服務器端將用戶提交的賬號,加密過的密碼保存到服務端的數據庫中,也就是服務 端并不會保存我們的明文密碼(原始)密碼! > * **Step 3**.說回客戶端,如果注冊成功或者登陸成功,你想保存賬號密碼到SP中,保存的的密碼 也需要走一趟加密流程!即明文密碼——&gt;加密,再保存!如果不保存,每次請求的時候,明文密碼 也要走一趟家里流程,然后拿著加密后的密碼來請求服務器! > * **Step 4**.服務器驗證賬號以及加密密碼,成功,分配客戶端一個session標識,后續客戶端可以拿著 這個session來訪問服務端提供的相關服務! 嘿嘿,理解了吧,加密的方法有很多種,小豬也不是這方面的高玩,以前使用過的加密方法是MD5 加密,本節也給大家簡單介紹一下這個MD5加密,以及演示下用法~ ### 2.MD5簡單介紹: **1)MD5是什么鬼?:** > 答:Message Digest Algorithm MD5(中文名為消息摘要算法第五版)為計算機安全領域廣泛 使用的一種散列函數,用以提供消息的完整性保護——摘自《百度百科》 簡單點說就是一種加密算法,可以將一個字符串,或者文件,壓縮包,執行MD5加密后, 就可以生產一個固定長度為128bit的串!這個串基本唯一!另外我們都知道:一個十六進制 需要用4個bit來表示,那么對應的MD5的字符串長度就為:128 / 4 = 32位了!另外可能 你看到一些md5是16位的,只是將32位MD5碼去掉了前八位以及后八位!不信么,我們來試試 百度一下:md5在線解密,第一個:[http://www.cmd5.com/](http://www.cmd5.com/) > > ![](http://www.runoob.com/wp-content/uploads/2015/09/62809654.jpg) **2)MD5能破解嗎?** > 答:MD5不可逆,就是說沒有對應的算法,無法從生成的md5值逆向得到原始數據! 當然暴力破解除外,簡單的MD5加密后可以查MD5庫~ **3)MD5值唯一嗎?** > 答:不唯一,一個原始數據只對應一個MD5值,但是一個MD5值可能對應多個原始數據! ### 3.MD5加密實現例子: 其實網上有很多寫好的MD5的例子,百度或者谷歌一搜一大堆,這里提供下小豬用的MD5加密工具類! **Md5Util.java**: ``` /** * Created by Jay on 2015/9/2 0002. */ public class MD5 { public static String getMD5(String content) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(content.getBytes()); return getHashString(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private static String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } } ``` **MainActivity.java**直接調用getMD5這個靜態方法: ``` Log.e("HeHe", MD5.getMD5("呵呵")); ``` 我們可以看到Logcat上打印出: ![](http://www.runoob.com/wp-content/uploads/2015/09/71453784.jpg) 這就是加密過后的呵呵了,我們可以把這串密文拷貝到上面這個md5的在線解密網站: ![](http://www.runoob.com/wp-content/uploads/2015/09/52984536.jpg) 嘿嘿,果然,只是這樣加密一次,就直接破解了,有點不安全的樣子,那就加密100次咯, 就是將加密后的字符串再加密,重復100次,我們在原先的基礎上加個加密一百次的方法: ``` public static String getMD5x100(String content){ String s1 = content; for(int i = 0;i < 100;i++){ s1 = getMD5(s1); } return s1; } ``` 然后調用下,發現打印這個的Log: ![](http://www.runoob.com/wp-content/uploads/2015/09/12090032.jpg) 復制界面網站上: ![](http://www.runoob.com/wp-content/uploads/2015/09/1147082.jpg) 好的,裝B成功~ ## 4.SharedPreference工具類: > 每次都要自行實例化SP相關的類,肯定很麻煩,這里貼個SP的工具類,大家可以貼到 自己的項目中,工具類來源于鴻洋大神的blog~ **SPUtils.java** ``` package com.jay.sharedpreferencedemo3; import android.content.Context; import android.content.SharedPreferences; import java.util.Map; /** * Created by Jay on 2015/9/2 0002. */ public class SPUtils { /** * 保存在手機里的SP文件名 */ public static final String FILE_NAME = "my_sp"; /** * 保存數據 */ public static void put(Context context, String key, Object obj) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); if (obj instanceof Boolean) { editor.putBoolean(key, (Boolean) obj); } else if (obj instanceof Float) { editor.putFloat(key, (Float) obj); } else if (obj instanceof Integer) { editor.putInt(key, (Integer) obj); } else if (obj instanceof Long) { editor.putLong(key, (Long) obj); } else { editor.putString(key, (String) obj); } editor.commit(); } /** * 獲取指定數據 */ public static Object get(Context context, String key, Object defaultObj) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE); if (defaultObj instanceof Boolean) { return sp.getBoolean(key, (Boolean) defaultObj); } else if (defaultObj instanceof Float) { return sp.getFloat(key, (Float) defaultObj); } else if (defaultObj instanceof Integer) { return sp.getInt(key, (Integer) defaultObj); } else if (defaultObj instanceof Long) { return sp.getLong(key, (Long) defaultObj); } else if (defaultObj instanceof String) { return sp.getString(key, (String) defaultObj); } return null; } /** * 刪除指定數據 */ public static void remove(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.remove(key); editor.commit(); } /** * 返回所有鍵值對 */ public static Map<String, ?> getAll(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE); Map<String, ?> map = sp.getAll(); return map; } /** * 刪除所有數據 */ public static void clear(Context context) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.clear(); editor.commit(); } /** * 檢查key對應的數據是否存在 */ public static boolean contains(Context context, String key) { SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE); return sp.contains(key); } } ``` ## 5.代碼下載: **SharedPreferenceDemo.zip**:[下載 SharedPreferenceDemo.zip](/try/download/SharedPreferenceDemo.zip) **SharedPreferenceDemo2.zip**:[下載 SharedPreferenceDemo2.zip](/try/download/SharedPreferenceDemo2.zip) **SharedPreferenceDemo3.zip**:[下載 SharedPreferenceDemo3.zip](/try/download/SharedPreferenceDemo3.zip) ## 本節小結: > 好的,關于Android存儲數據的第二種方式:SharedPreference保存用戶偏好參數的內容就這么多, 應該可以滿足你日常開發使用SP的需求,如果有什么遺漏,歡迎提出,謝謝~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看