Shared Preference将一组原始数据的NVP(name-value pair)存储为命名首选项(named preference).
创建SharedPreferences类使用getSharedPreferences(), 并传入要SharedPreferences的名称;
修改SharedPreferences类使用SharedPreferences.Editor类, 通过调用SharedPreferences类的edit()方法, 获取对象;
使用SharedPreferences.Editor类的put<type>()方法进行修改相关的名称(name)的值(value);
使用SharedPreferences.Editor类的apply()方法进行异步保存;
注意:保存可以使用apply()方法和commit()方法, 但是apply()方法是首选.
apply()方法是异步保存, commit()方法是同步保存, 需要阻止调用线程, 判断返回, 所以优先选择apply()方法.
访问SharedPreferences类, 使用getSharedPreferences()方法, 即与创建类似;
使用SharedPreferences类的get<type>()方法, 返回保存的值, 需要一个命名(name), 即键(key), 和一个默认值, 当没有值时使用默认.
使用SharedPreferences类的getAll()方法, 返回所有映射, 可以通过contains()方法, 返回boolean类型, 判断是否存在.
具体参考Android API: http://[防禁用]developer.android.com/guide/topics/data/data-storage.html
查看本栏目更多精彩内容:http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/
代码:
package mzx.spike.earthquake.app; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import java.util.Map; /** * Created by Spike on 2014/4/25. */ public class Test extends Activity { public static final String MY_PREFS = "MyPrefs"; @Override protected void onCreate(Bundle state){ super.onCreate(state); // Restore preferences SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = mySharedPreferences.edit(); editor.putBoolean("isTrue", true); editor.putFloat("lastFloat", 1f); editor.putInt("wholeNumber", 2); editor.putLong("aNumber", 31); editor.putString("textEntryValue", "Not Empty"); editor.commit(); boolean isTrue = mySharedPreferences.getBoolean("isTrue", false); float lastFloat = mySharedPreferences.getFloat("lastFloat", 0f); int wholeNumber = mySharedPreferences.getInt("wholeNumber", 1); long aNumber = mySharedPreferences.getLong("aNumber", 0); String textEntryValue = mySharedPreferences.getString("textEntryValue", ""); Map<String, ?> allPreferences = mySharedPreferences.getAll(); boolean containsLastFloat = mySharedPreferences.contains("lastFloat"); } }
作者:csdn博客 Spike_King
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
, 方法
, sharedpreferences
, editor
, 分享android
, apply
, android分享
, android首选项
, Android首选项框架
, Android判断app
android调用分享
sharedpreference、安卓sharedpreference、遍历sharedpreference、sharedpreference权限、清空sharedpreference,以便于您获取更多的相关知识。