24SharedPreferences的工具类的编写

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);
	}
}

这个类是单例类。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值