Android本地存儲(chǔ)SharedPreferences詳解
Android本地存儲(chǔ)SharedPreferences詳解
存儲(chǔ)位置
SharedPreferences數(shù)據(jù)保存在: /data /data/<package_name> /shared_prefs 文件夾下,以XML格式保存,根元素為:<map />。文件名稱為獲取SharedPreferences實(shí)例時(shí)傳遞的參數(shù)值。
<map> <int name="key" value="value" /> <string name="key" > value </string> </map>
獲取實(shí)例
SharePerferences是一個(gè)接口,Context實(shí)現(xiàn)了API:getSharedPreferences(String, int);這個(gè)API依據(jù)String返回一個(gè)SharePerferences實(shí)例。同樣的String返回的SharePerferences的實(shí)例是同樣的。此處strign指定的是存儲(chǔ)數(shù)據(jù)的xml文件的名稱。
Activity實(shí)現(xiàn)了getPreferences(int),這種方法就是默認(rèn)使用Activity的class name作為String調(diào)用 getSharedPreferences(String, int)。
//指定該SharedPreferences數(shù)據(jù)僅僅能被本應(yīng)用讀、寫。 Context.MODE_PRIVATE //指定該SharedPreferences數(shù)據(jù)也能被其它應(yīng)用程序讀,但不能寫。 Context.MODE_WORLD_READABLE //指定該SharedPreferences數(shù)據(jù)也能被其它應(yīng)用程序讀、寫。 Context.MODE_WORLD_WRITEABLE //文件是否存在,存在那么追加,否則新建 Context.MODE_WORLD_APPEND
讀
//推斷SharedPreferences是否包括特定key的數(shù)據(jù)。 boolean contains(String key) //獲取SharedPreferences里所有的key-value對。 Map<String,?> getAll() //獲取指定key相應(yīng)的value,假設(shè)key不存在。則返回默認(rèn)值defValue。 Xxx getXxx(String key, Xxx defValue)
寫
SharedPreferences接口本身未提供寫入數(shù)據(jù)的能力,而是通過其內(nèi)部接口。其調(diào)用SharedPreferences.edit() 方法就可以獲得它所相應(yīng)的 SharedPreferences.Editor對象。Editor有例如以下向SharedPreferences寫入數(shù)據(jù)的方法: //清空SharedPreferences里全部數(shù)據(jù)。 Editor.clear() //向SharedPreferences里存入指定key相應(yīng)的數(shù)據(jù)。 Editor.putXxx(String key, Xxx Value) //刪除SharedPreferences里指定key相應(yīng)的數(shù)據(jù)項(xiàng)。 Editor.remove(String key) //當(dāng)Editor編輯完畢后,調(diào)用該方法提交改動(dòng)。 boolean Editor.commit()
讀寫其它應(yīng)用的SharedPreferences
1.創(chuàng)建其它應(yīng)用的相應(yīng) Context。
Context useContext =createPackageContext("package_name",Context.CONTEXT_IGNORE_SECURITY);
2.調(diào)用其它應(yīng)用的 Context的 getSharedPreferences()方法獲取 SharedPreferences對象。
3.調(diào)用其它應(yīng)用的 SharedPreferences.edit()方法獲得對應(yīng)SharedPreferences.Editor對象。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Win10下android studio開發(fā)環(huán)境配置圖文教程
這篇文章主要為大家詳細(xì)介紹了Win10下android studio開發(fā)環(huán)境配置圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-07-07Android Studio利用AChartEngine制作餅圖的方法
閑來無事,發(fā)現(xiàn)市面上好多app都有餅圖統(tǒng)計(jì)的功能,得空自己實(shí)現(xiàn)一下,下面這篇文章主要給大家介紹了關(guān)于Android Studio利用AChartEngine制作餅圖的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧2018-10-10解析后臺(tái)進(jìn)程對Android性能影響的詳解
本篇文章是對Android中后臺(tái)進(jìn)程對Android性能的影響進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05詳解Android Service 使用時(shí)的注意事項(xiàng)
這篇文章主要介紹了詳解Android Service 使用時(shí)的注意事項(xiàng),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10ContentProvider客戶端處理provider邏輯分析
這篇文章主要為大家介紹了ContentProvider客戶端處理provider邏輯分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10Android自定義View實(shí)現(xiàn)抽獎(jiǎng)轉(zhuǎn)盤
這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)抽獎(jiǎng)轉(zhuǎn)盤,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12