android資料存放區與訪問之使用SharedPreferences

來源:互聯網
上載者:User

很多時候我們開發的軟體需要向使用者提供軟體參數設定功能,例如我們常用的QQ,使用者可以設定是否允許陌生人添加自己為好友。對於軟體配置參數的儲存,如果是window軟體通常我們會採用ini檔案進行儲存,如果是j2se應用,我們會採用properties屬性檔案或者xml進行儲存。如果是Android應用,我們最適合採用什麼方式儲存軟體配置參數呢?Android平台給我們提供了一個SharedPreferences類,它是一個輕量級的儲存類,特別適合用於儲存軟體配置參數。使用SharedPreferences儲存資料,其背後是用xml檔案存放資料,檔案存放在/data/data/<package
name>/shared_prefs目錄下:

SharedPreferences sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();//擷取編輯器
editor.putString("name", "laotian");
editor.putInt("age", 4);

editor.commit();//提交修改

產生的config.xml檔案內容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">laotian</string>
<int name="age" value="4" />
</map>
因為SharedPreferences背後是使用xml檔案儲存資料,getSharedPreferences(name,mode)方法的第一個參數用於指定該檔案的名稱,名稱不用帶尾碼,尾碼會由Android自動加上。方法的第二個參數指定檔案的操作模式,共有四種操作模式,這四種模式前面介紹使用檔案方式儲存資料時已經講解過。如果希望SharedPreferences背後使用的xml檔案能被其他應用讀和寫,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE許可權。
另外Activity還提供了另一個getPreferences(mode)方法操作SharedPreferences,這個方法預設使用當前類不帶包名的類名作為檔案的名稱。

訪問SharedPreferences中的資料代碼如下:
SharedPreferences sharedPreferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
//getString()第二個參數為預設值,如果preference中不存在該key,將返回預設值

String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);

如果訪問其他應用中的Preference,前提條件是:該preference建立時指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE許可權。如:有個<package name>為cn.itcast.action的應用使用下面語句建立了preference。
getSharedPreferences("itcast", Context.MODE_WORLD_READABLE);
其他應用要訪問上面應用的preference,首先需要建立上面應用的Context,然後通過Context 訪問preference ,訪問preference時會在應用所在包下的shared_prefs目錄找到preference :

Context otherAppsContext = createPackageContext("com.oce.action", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("config", Context.MODE_WORLD_READABLE);
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 0);

如果不通過建立Context訪問其他應用的preference,也可以以讀取xml檔案方式直接存取其他應用preference對應的xml檔案,如:
File xmlFile = new File(“/data/data/<package name>/shared_prefs/itcast.xml”);//<package name>應替換成應用的包名

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.