SharedPreferences简介

来源:互联网 发布:上海神机妙算软件定额 编辑:程序博客网 时间:2024/06/07 00:20
  public interface
SharedPreferences
android.content.SharedPreferences
SharedPreferences是以键值对来存储应用程序的配置信息的一种方式,它只能存储基本数据类型。
实际上
SharedPreferences是采用了XML格式将数据存储到设备中,它
在DDMS中的File Explorer中的
/data/data/<package name>/shares_prefs下。
以下为获取 SharedPreferences对象的两个方法:
通过Context的以下方法

public abstract SharedPreferences getSharedPreferences (String name, int mode)

Since: API Level 1

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.

Parameters
nameDesired 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()).
name为本组件的配置文件名(如果想要与本应用程序的其他组件共享此配置文件,可以用这个名字来检索到这个配置文件)。modeOperating 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. 
mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和 MODE_WORLD_WRITEABLE。
Returns
  • Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.
See Also
  • MODE_PRIVATE
  • MODE_WORLD_READABLE
  • MODE_WORLD_WRITEABLE
  • MODE_MULTI_PROCESS   
通过Activity对象的以下方法

public SharedPreferences getPreferences (int mode)

Since: API Level 1

Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlyinggetSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.

Parameters
modeOperating mode. Use MODE_PRIVATE for the default operation, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
Returns
  • Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.
该方法其实是以Activity的名字作为name参数调用Context.getSharedPreferences(String name,int mode)
mode为操作模式,默认的模式为0或MODE_PRIVATE,还可以使用MODE_WORLD_READABLE和 MODE_WORLD_WRITEABLE。


如果要读取SharedPreferences的信息,只需要直接使用SharedPreferences对象的getXXX()方法即可,
而如果要写入配置信息,则必须先调用SharedPreferences 对象的edit()方法,
得到SharedPreferences.Editor对象,然后再调用Editor的putXXX()方法写入配置信息,
最后调用Editor的commit()方法提交更改后的配置文件。


因为 很多程序都有这个需要 所以可以自己把该功能集成并列出一些接口函数 以后用的话会方便很多。
SharedPreferencesResolver.java文件

package com.teleca.util;import java.util.Map;import android.content.Context;import android.content.SharedPreferences;public class SharedPreferencesResolver {    SharedPreferences.Editor editor;    Context context;    SharedPreferences sp;    public SharedPreferencesResolver(Context c, String name,int mode) {        context = c;        sp = context.getSharedPreferences(name, mode);    }     public final boolean contains(String  key)      {          return sp.contains(key);      }     public final Map<String, ?> getAll()     {         return sp.getAll();     }    public final String getValue(String key,String defaultValue){           return sp.getString(key, defaultValue);      }    public final boolean getValue(String key,boolean defaultValue){           return sp.getBoolean(key, defaultValue);      }    public final float getValue(String key,float defaultValue){           return sp.getFloat(key, defaultValue);      }     public final int getValue(String key,int defaultValue){           return sp.getInt(key, defaultValue);      }     public final long getValue(String key,long defaultValue){           return sp.getLong(key, defaultValue);      }     public final void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener  listener)     {         sp.registerOnSharedPreferenceChangeListener(listener);     }     public final void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener  listener)     {         sp.unregisterOnSharedPreferenceChangeListener(listener);     }    public final void OpenEditor() {        if(editor==null)        editor = sp.edit();    }    public final void clearEditor()    {        editor.clear();    }    public final void putValue(String key, String value) {        editor.putString(key, value);    }    public final void putValue(String key, boolean value) {        editor.putBoolean(key, value);    }    public final void putValue(String key, float value) {        editor.putFloat(key, value);    }    public final void putValue(String key, int value) {        editor.putInt(key, value);    }    public final void putValue(String key, long value) {        editor.putLong(key, value);    }    public final void remove(String key)    {        editor.remove(key);    }    public final void commitEditor() {        if (editor != null)            editor.commit();    }    public final void closeEditor() {        editor=null;    }}

访问本应用程序的SharedPreferences:

        String spName="contacts";        int spMode=Context.MODE_WORLD_WRITEABLE|Context.MODE_WORLD_READABLE;        SharedPreferencesResolver spResolver=new SharedPreferencesResolver(Hello.this,spName,spMode);        spResolver.OpenEditor();        spResolver.putValue("name", "hubin");        spResolver.putValue("phone", "13880890660");        spResolver.commitEditor();        spResolver.closeEditor();        Log.i(tag, spResolver.getValue("name", ""));        Log.i(tag, spResolver.getValue("phone", ""));

这里用Context.MODE_WORLD_WRITEABLE|Context.MODE_WORLD_READABLE表示所有应用程序都对它可读可写。
跨包访问另外一个应用程序的SharedPreferences.

        try {            Context otherContext = this.createPackageContext("com.teleca", Context.CONTEXT_IGNORE_SECURITY);            String name = "contacts";            int mode = Context.MODE_WORLD_WRITEABLE;            SharedPreferences sp = otherContext                    .getSharedPreferences(name, mode);            Log.i(tag, "name:" + sp.getString("name", "NA"));            Log.i(tag, "phone:" + sp.getString("phone", "NA"));            SharedPreferences.Editor editor = sp.edit();            editor.putString("wife", "yangyang");            editor.commit();            Log.i(tag, "wife:" + sp.getString("wife", "NA"));        } catch (NameNotFoundException e) {            Log.e(tag, "Erro:", e);        }

注意需要在SharedPreferences创建时通过mode参数来设置非本地应用程序的访问权限。
Context.MODE_WORLD_WRITEABLE 所有应用程序对它可写。
Context.MODE_WORLD_READABLE 所有应用程序对它可读。
Context.MODE_WORLD_WRITEABLE|Context.MODE_WORLD_READABLE所有应用程序都对它可读可写。
运行使用相同用户ID的一组应用程序
    有时,设置应用程序的用户ID是极为有用的(大多数情况下,较好的方式是让平台选择一个唯一的ID)。
如果多个应用程序需要在相互之间存储数据。但是你不希望这些数据被其他应用程序访问,
则可以将权限设置为私有并共享UID来允许访问。可以在mainfest文件中使用ShareUserId属性来共享UID。
android:sharedUserId="YourFancyID"
关于跨包访问Preferences的更多内容请参考《跨包访问Preferences》
原创粉丝点击