Android local storage SharedPreferences detailed explanation
Storage location
SharedPreferences data is saved in: /data /data/<package_name> /shared_prefs In the folder, save it in XML format, the root element is: <map />. The file name is the parameter value passed when getting the SharedPreferences instance.
<map> <int name="key" value="value" /> <string name="key" > value </string> </map>
Get an instance
SharePerferences is an interface, and Context implements API: getSharedPreferences(String, int); this API returns a SharePerferences instance based on String. The same String returns the SharePerferences instances. Here string specifies the name of the xml file that stores the data.
Activity implements getPreferences(int), which is to use the Activity class name as String to call getSharedPreferences(String, int) by default.
//Specify that the SharedPreferences data can only be read and written by this application. Context.MODE_PRIVATE //Specify that the SharedPreferences data can also be read by other applications, but cannot be written.Context.MODE_WORLD_READABLE //Specify that the SharedPreferences data can also be read and written by other applications.Context.MODE_WORLD_WRITEABLE //If the file exists, then add it, otherwise create a new oneContext.MODE_WORLD_APPEND
read
//Infer whether SharedPreferences includes data for a specific key.boolean contains(String key) //Get all key-value pairs in SharedPreferences.Map<String,?> getAll() //Get the corresponding value of the specified key, assuming that the key does not exist. The default value is defValue. Xxx getXxx(String key, Xxx defValue)
Write
SharedPreferencesThe interface itself does not provide the ability to write data,Instead, through its internal interface。Its call() The method can obtain the corresponding Object。EditorThere are, for example, the followingSharedPreferencesHow to write data: //Clear all data in SharedPreferences.() //Storage the corresponding data of the specified key into SharedPreferences. (String key, Xxx Value) //Delete the corresponding data item specified in SharedPreferences. (String key) //When the Editor is finished editing, call this method to submit changes.boolean ()
SharedPreferences for reading and writing other applications
1. Create a response to other applications Context.
Context useContext =createPackageContext("package_name",Context.CONTEXT_IGNORE_SECURITY);
2. Call the getSharedPreferences() method of the Context of other applications to get the SharedPreferences object.
3. Call the () method of other applications to obtain the corresponding object.
Thank you for reading, I hope it can help you. Thank you for your support for this site!