public class SpInstance {
/ * SP_NAME sp的名称 * applicationContext 上下文 * sharedPreferences sp */ public static final String SP_NAME = "my_sp_config"; private Context applicationContext = null; private SharedPreferences sharedPreferences = null; public static final int ERROR_CODE = -1; / * instance 单例 * INSTANCE_LOCK 互斥锁 */ private static SpInstance instance = null; private static final Object INSTANCE_LOCK = new Object(); / * 获取单例 * * @return */ public static SpInstance getInstance() {
if (instance == null) {
synchronized (INSTANCE_LOCK) {
if (instance == null) {
instance = new SpInstance(); } } } return instance; } / * 初始化 * * @param context */ public void init(Context context) {
this.applicationContext = context.getApplicationContext(); } / * 获取 sp * * @return */ private SharedPreferences getSp() {
if (sharedPreferences == null) {
sharedPreferences = applicationContext.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE); } return sharedPreferences; } / * 获取编辑 * * @return */ private SharedPreferences.Editor getEdit() {
return getSp().edit(); } / * 存值至 sp * * @param key * @param value * @param <T> */ public <T> void put(String key, T value) {
if (getEdit() != null) {
if (value instanceof Boolean) {
getEdit().putBoolean(key, (Boolean) value).commit(); } else if (value instanceof String) {
getEdit().putString(key, (String) value).commit(); } else if (value instanceof Integer) {
getEdit().putInt(key, (Integer) value).commit(); } else if (value instanceof Float) {
getEdit().putFloat(key, (Float) value).commit(); } else if (value instanceof Long) {
getEdit().putLong(key, (Long) value).commit(); } } } public boolean getBoolean(String key, boolean defaultValue) {
if (getSp() != null) {
return getSp().getBoolean(key, defaultValue); } return false; } public String getString(String key, String defaultValue) {
if (getSp() != null) {
return getSp().getString(key, defaultValue); } return ""; } public int getInt(String key, int defaultValue) {
if (getSp() != null) {
return getSp().getInt(key, defaultValue); } return ERROR_CODE; } public float getFloat(String key, float defaultValue) {
if (getSp() != null) {
return getSp().getFloat(key, defaultValue); } return ERROR_CODE; } public long getLong(String key, long defaultValue) {
if (getSp() != null) {
return getSp().getLong(key, defaultValue); } return ERROR_CODE; } }
讯享网
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/62146.html