【Based Android】Android Sharedpreferences實現使用者偏好儲存

來源:互聯網
上載者:User

在開發應用程式的過程中,有時候我們需要記錄使用者的偏好,或者使用者名稱密碼之類。這就要涉及到資料的儲存,android平台下儲存資料的方式主要有如下幾種方式:

  

Shared PreferencesStore private primitive data in key-value pairs.

 輕量的以索引值對的形式進行儲存

Internal StorageStore private data on the device memory.

裝置上的檔案儲存體

External StorageStore public data on the shared external storage.

外部的檔案儲存體,一般指儲存在SD卡上的檔案,優勢是不隨程式卸載而刪除

SQLite DatabasesStore structured data in a private database.

這個比較常見了資料庫

Network ConnectionStore data on the web with your own network server.  

網路擷取

 

     那麼今天主要和大家分享的是第一種Shareepreference ,這是android提供的一個輕量級的資料存放區架構,形式就是索引值對的形式,熟悉xml的朋友應該比較習慣這種風格,就是“屬性名稱-屬性值”的形式。從名字就可以看出,這個架構主要是用於設定使用者的一個偏好,他的一個特點是可以跨session的共用,在多個activity之間可以操作,如果設定特別的許可權,其他應用也可以訪問。下面就是使用的一個基本方法。

    1:擷取類型SharedPreferences 

     主要有兩種方式可以獲得

      

  • getSharedPreferences() 接受兩個參數,第一個是檔案標示,第二個是許可權,用於建立多個設定檔的情境
  • getPreferences() - 只有檔案許可權參數,與上一個不同在於只建立一個檔案。

   今天詳細介紹一下第一個方法~

 

   首先看來自官方API的介紹

 

public abstract SharedPreferences getSharedPreferences (String name, int mode)

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

解釋:該方法用於從上下文,(可以理解為我們的Context檔案,相信寫過各種服務的朋友並不陌生)取回並維護一個名為name的設定檔。返回一個SharedPreferences對象,我們可以通過這個對象編輯和擷取索引值。每一個時刻只有一個SharedPreferencesd執行個體會被調用。效果是,每一個調用者可以立刻看到其他調用者編輯的效果。

Parameters
name  Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
解釋:需要的檔案名稱字,如果不存在的話,當你調用editor的時候(用於編輯偏好檔案,下面會介紹)會自動建立。
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions. The bit MODE_MULTI_PROCESS can also be used if multiple processes are mutating the same SharedPreferences file.MODE_MULTI_PROCESS is always on in apps targetting Gingerbread (Android 2.3) and below, and off by default in later versions.

解釋:操作模式 一共有四種,下面逐一解釋

Returns
  • Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.
See Also
  • MODE_PRIVATE         這是預設的形式,設定檔只允許本程式和享有本程式ID的程式的訪問
  • MODE_WORLD_READABLE   允許其他的應用程式讀檔案
  • MODE_WORLD_WRITEABLE   允許其他的應用程式寫檔案
  • MODE_MULTI_PROCESS       主要用於多任務,2.3版本當多個進程共同訪問的時候,必須指定這個標籤

有了SharedPreferences對象我們還需要一個Editor來進行偏好的編輯與設定。

    Editor主要包含一些putXXX方法,支援booleans, floats, ints, longs, and strings.幾種類型,最後完成添加後,一定要調用commit方法或者apply方法進行修改後的提交。

 

    如果想得到value的話就自己直接用SharedPreference類來使用相應的getxxx方法就好了。

    不多說了,奉上一段自己臨時寫的一段非常簡單的代碼,與大家分享

 1 package com.yui;  
2
3 import android.content.Context;
4 import android.content.SharedPreferences;
5 import android.content.SharedPreferences.Editor;
6 import android.os.Bundle;
7 import android.preference.PreferenceActivity;
8 import android.util.Log;
9 /**
10 * 示範android SharedPreference的一個demo
11 * @author Octobershiner
12 * @version 1.0 2011/11/4
13 * */
14 public class PreferActivity extends PreferenceActivity {
15 /** Called when the activity is first created. */
16
17 //設定一些標籤
18 private static final String MY_SETTING = "mySetting";
19 private static final String COLOR = "color";
20 private static final String DEFAULT_COLOR = "blue";
21
22 @Override
23 public void onCreate(Bundle savedInstanceState) {
24 super.onCreate(savedInstanceState);
25 setContentView(R.layout.main);
26
27 //get the setting files
28 SharedPreferences myPreference = this.getSharedPreferences(MY_SETTING, Context.MODE_PRIVATE);
29 //edit the file
30 Editor editor = myPreference.edit();
31 editor.putString(COLOR, "red");
32
33 /**
34 * 解釋一下這個函數,當myPreference發現沒有COLOR屬性存在的時候
35 * 會將DEFAULT_COLOR的賦給temp
36 * 大家可以試一下把前面的putString注釋掉,log的記過就不同了
37 * */
38 String temp = myPreference.getString(COLOR, DEFAULT_COLOR);
39 //利用Log顯示一些結果
40 Log.i("TAG","now i prefer "+temp);
41 }
42 }

在最後,我想問一個問題,小O是看了android 2.3的SDK原始碼,但是發現,SharedPreference只是一個介面,我並沒有找到它的實現,網上也沒有相應的解答,希望瞭解的朋友能及時的聯絡我,交流一下,謝謝,十一點了,實驗室沒人了,準備回去睡覺~~

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.