比較簡單,話不多說,直接源碼
import android.content.Context;
import android.content.SharedPreferences;
/**
* 偏好設定工具類
*/
public class ShareUtils {
public static final String NAME = "config.hxd";
/**
* 存入資料(String)
*/
public static void putString(Context context, String key, String value) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
//向偏好設定内部添加資料并且送出
spf.edit().putString(key, value).commit();
}
/**
* 取資料(上下文,鑰匙,未取得資料傳回的預設值)(String)
*/
public static String getString(Context context, String key, String value) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
//傳回需要取得的資料
return spf.getString(key, value);
}
/**
* 存入資料(Int)
*/
public static void putInt(Context context, String key, int value) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
//向偏好設定内部添加資料并且送出
spf.edit().putInt(key, value).commit();
}
/**
* 取資料(上下文,鑰匙,未取得資料傳回的預設值)(Int)
*/
public static int getInt(Context context, String key, int value) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
//傳回需要取得的資料
return spf.getInt(key, value);
}
/**
* 存入資料(Int)
*/
public static void putBoolean(Context context, String key, boolean value) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
//向偏好設定内部添加資料并且送出
spf.edit().putBoolean(key, value).commit();
}
/**
* 取資料(上下文,鑰匙,未取得資料傳回的預設值)(Int)
*/
public static boolean getBoolean(Context context, String key, boolean value) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
//傳回需要取得的資料
return spf.getBoolean(key, value);
}
/**
* 删除單個偏好設定
*/
public static void deleteShare(Context context, String key) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
spf.edit().remove(key).commit();
}
/**
* 删除單個偏好設定
*/
public static void deleteShareAll(Context context, String key) {
//獲得偏好設定
SharedPreferences spf = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
spf.edit().clear().commit();
}
}