SharedPreferences的工具类主要用来保存用户的偏好设置的数据:
package com.dystu.impro.utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* SharedPreferences的工具类,本例为单例类
*
* 主要用来保存用户的偏好设置(比如新消息提醒,声音,震动,扬声器)
*
*
* @author
*
*/
public class CXPreferenceUtils {
/*
* SharedPreferences保存的名称
*/
public static final String PREFRENCE_NAME = "saveInfo";
private static SharedPreferences mSharedPreferences;
private static CXPreferenceUtils mPreferenceUtils;
private static SharedPreferences.Editor editor;
private String SHARED_KEY_SETTING_NOTIFICATION = "shared_key_setting_notification";
private String SHARED_KEY_SETTING_SOUND = "shared_key_setting_sound";
private String SHARED_KEY_SETTING_VIBRATE = "shared_key_setting_vibrate";
private String SHARED_KEY_SETTING_SPEAKER = "shared_key_setting_speaker";
private CXPreferenceUtils(Context ctx) {
mSharedPreferences = ctx.getSharedPreferences(PREFRENCE_NAME,
Context.MODE_PRIVATE);
editor = mSharedPreferences.edit();
}
/**
* synchronized保证多线程下的安全性
*
* @param ctx
*/
public static synchronized void init(Context ctx) {
if (mPreferenceUtils == null) {
mPreferenceUtils = new CXPreferenceUtils(ctx);
}
}
/**
* 单例模式,获取instance实例
*
* @return
*/
public static CXPreferenceUtils getInstance() {
if (mPreferenceUtils == null) {
throw new RuntimeException("please init first");
}
return mPreferenceUtils;
}
public void setSettingMsgNotification(boolean paramBoolean) {
editor.putBoolean(SHARED_KEY_SETTING_NOTIFICATION, paramBoolean);
editor.commit();
}
public boolean getSettingMsgNotification() {
return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_NOTIFICATION,
true);
}
public void setSettingMsgSound(boolean paramBoolean) {
editor.putBoolean(SHARED_KEY_SETTING_SOUND, paramBoolean);
editor.commit();
}
public boolean getSettingMsgSound() {
return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_SOUND, true);
}
public void setSettingMsgVibrate(boolean paramBoolean) {
editor.putBoolean(SHARED_KEY_SETTING_VIBRATE, paramBoolean);
editor.commit();
}
public boolean getSettingMsgVibrate() {
return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_VIBRATE, true);
}
public void setSettingMsgSpeaker(boolean paramBoolean) {
editor.putBoolean(SHARED_KEY_SETTING_SPEAKER, paramBoolean);
editor.commit();
}
public boolean getSettingMsgSpeaker() {
return mSharedPreferences.getBoolean(SHARED_KEY_SETTING_SPEAKER, true);
}
}
这个类是单例类。