An analysis of the internal principle of Android Sharedpreferences

Source: Internet
Author: User

sharedpreferences Internal working principle:

1. Call Getsharedpreferences (); Create a Sharedpreferences object that will first determine if there is a corresponding XML file and, if found, there will be a preload operation. This is done by parsing the contents of the XML file into a map object after I/O operation and XMLUITL, so we call sharedpreferences::getstring (); The get operation is actually not I/O to the file. Instead, it directly accesses the content of the new map collection, which improves efficiency and re-creates a corresponding XML file if the corresponding XML does not exist.
Some implementations are as follows:

@Override    public SharedPreferences getSharedPreferences(String name, int mode) {        SharedPreferencesImpl sp;//...             sp = packagePrefs.get(name);            if (sp == null) {                File prefsFile = getSharedPrefsFile(name);                //该构造方法会调用startLoadFromDisk();把数据从硬盘加载到内存                sp = new SharedPreferencesImpl(prefsFile, mode);                packagePrefs.put(name, sp);                return sp;            }//...        return sp;    }

2, put write operation: write operation also has two steps, one is to write the data first in memory, that is, the map collection, and the second is to write data to the hard disk file. This will ensure the integrity of the data, the write operation has two ways to commit:

Commit (): Thread-safe, slow performance, generally in the current thread to complete the write file operation
Apply (): thread insecure, high performance, asynchronous processing IO operation, will certainly put this write file operation into a singlethreadexecutor thread pool processing

3, Sharedpreferences will maintain a singleton after the first creation, and each call to Getsharedpreferences () returns a unique instance

 sharedpreferences a  = g Etsharedpreferences ( "test" , 0 )  Sharedpreferences B = getsharedpreferences ( "test" , 0        )  Sharedpreferences C = getsharedpreferences ( "test" , 0        )  LOG.I (TAG,  "Result:"  + (a  ==b) +", " + (B==c)")  //12-04 13:38:17.811 2287-2287/com.sunzxy.myapplication i/mainactivity:result:  true , true   

Sharedpreferences using encapsulation:
Since Sharedpreferences's key and value are all actually in the string type, you can write a Sharedpreferences tool class like this:

/** * Created by Sunzxyong on 15/12/4. * * Public  class perferencemanager {    Private Static FinalString Perf_name ="Com.suznxyong.util.my_perf";Private Static Final intCurrent_version_code =1;Private volatile StaticPerferencemanager instance;Private FinalSharedpreferences preferences;Private Perferencemanager(Context context)        {preferences = Context.getsharedpreferences (Perf_name, context.mode_private);    Checkprefversion (); } Public StaticPerferencemanagergetinstance(Context context) {if(Instance = =NULL) {synchronized(Perferencemanager.class) {if(Instance = =NULL) Instance =NewPerferencemanager (context); }        }returnInstance } Public Final void Putvalue(string key, String value)    {Preferences.edit (). putstring (key, value). Apply (); } Public FinalStringGetValue(String key) {Checkislegal (key);returnPreferences.getstring (Key,""); } Public Final void DeleteValue(String key)        {Checkislegal (key);    Preferences.edit (). Remove (key). Apply (); } Public Final void Clear() {Preferences.edit (). Clear (). apply (); }Private void Checkislegal(String key) {if(Textutils.isempty (key))Throw NewIllegalArgumentException ("This parameter is Illegal,key:"+ key); }Private void checkprefversion() {Final intOldversion = Preferences.getint (Perf_name,0);if(Oldversion < Current_version_code) {Preferences.edit (). Clear (). Putint (Perf_name, Current_version_code). AP        Ply (); }    }}

Since the application version upgrade does not delete the Sharedpreferences file, so you can add a version to judge, to do some data updates, from the above view, because every call Getsharedpreferences () will have IO operation, when the content is more than a long time, Then it is not appropriate to application in the OnCreate of the Sharedpreferences file initialization, the best way is to open a sub-thread to complete its creation and data pre-loading!!!

An analysis of the internal principle of Android Sharedpreferences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.