下面列出了android.content.Context#getSharedPreferences ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = context.getSharedPreferences(context.getPackageName() + "_preferences", Context.MODE_MULTI_PROCESS);
boolean wifiOnly = prefs.getBoolean("wifi_only", false);
boolean chargingOnly = prefs.getBoolean("charging_only", false);
String action = intent.getAction();
if((wifiOnly && DeviceUtil.isWifi(context) && action.equals("android.net.wifi.STATE_CHANGE")) || (chargingOnly && action.equals("android.intent.action.ACTION_POWER_CONNECTED"))){
AccountManager am = AccountManager.get(context);
Account[] accs = am.getAccountsByType(context.getString(R.string.ACCOUNT_TYPE));
if (accs.length > 0){
Account account = accs[0];
SharedPreferences.Editor editor = prefs.edit();
if (prefs.getBoolean("missed_contact_sync", false)){
ContentResolver.requestSync(account, ContactsContract.AUTHORITY, new Bundle());
editor.putBoolean("missed_contact_sync", false);
}
if (prefs.getBoolean("missed_calendar_sync", false)){
ContentResolver.requestSync(account, CalendarContract.AUTHORITY, new Bundle());
editor.putBoolean("missed_calendar_sync", false);
}
editor.commit();
}
}
}
/**
* 从文件中读取数据
*
* @param context
* @param key
* @param defValue
* @return
*/
public static Object getData(Context context, String key, Object defValue) {
String type = defValue.getClass().getSimpleName();
SharedPreferences sharedPreferences = context.getSharedPreferences
(FILE_NAME, Context.MODE_PRIVATE);
//defValue为为默认值,如果当前获取不到数据就返回它
if ("Integer".equals(type)) {
return sharedPreferences.getInt(key, (Integer) defValue);
} else if ("Boolean".equals(type)) {
return sharedPreferences.getBoolean(key, (Boolean) defValue);
} else if ("String".equals(type)) {
return sharedPreferences.getString(key, (String) defValue);
} else if ("Float".equals(type)) {
return sharedPreferences.getFloat(key, (Float) defValue);
} else if ("Long".equals(type)) {
return sharedPreferences.getLong(key, (Long) defValue);
}
return null;
}
/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
*
* @param context
* @param key
* @param object
*/
public static void put(Context context, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
editor.putLong(key, (Long) object);
} else {
editor.putString(key, object.toString());
}
SharedPreferencesCompat.apply(editor);
}
public synchronized static String getUniqueId(Context context) {
if (uniqueID == null) {
SharedPreferences sharedPrefs = context.getSharedPreferences(
PREF_UNIQUE_ID, Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
uniqueID = UUID.randomUUID().toString();
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString(PREF_UNIQUE_ID, uniqueID);
editor.commit();
}
}
return uniqueID;
}
/**
* 将对象从 SharedPreference 中取出来
*
* @param context Context
* @param key Key
* @return T 自定义类对象
*/
public static <T> T getDeviceData(Context context, String key) {
if (mSharedPreferences == null) {
mSharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
}
T device = null;
String productBase64 = mSharedPreferences.getString(key, null);
if (productBase64 == null) {
return null;
}
//读取字节
byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT);
//封装到字节流
ByteArrayInputStream stream = new ByteArrayInputStream(base64);
try {
//再次封装
ObjectInputStream bis = new ObjectInputStream(stream);
// 读取对象
device = (T) bis.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return device;
}
static RemoteViews updateWidget(final int appWidgetId, final Context context, final int steps) {
final SharedPreferences prefs =
context.getSharedPreferences("Widgets", Context.MODE_PRIVATE);
final PendingIntent pendingIntent = PendingIntent
.getActivity(context, appWidgetId, new Intent(context, Activity_Main.class), 0);
final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.widget, pendingIntent);
views.setTextColor(R.id.widgetsteps, prefs.getInt("color_" + appWidgetId, Color.WHITE));
views.setTextViewText(R.id.widgetsteps, String.valueOf(steps));
views.setTextColor(R.id.widgettext, prefs.getInt("color_" + appWidgetId, Color.WHITE));
views.setInt(R.id.widget, "setBackgroundColor",
prefs.getInt("background_" + appWidgetId, Color.TRANSPARENT));
return views;
}
/**
* 获取分组信息
*
* @param context
* @param key
* @return
*/
public static List<String> getGroup(Context context, String key) {
SharedPreferences sharedPreferences = context
.getSharedPreferences(FILE_NAME_GROUP, Context.MODE_PRIVATE);
String group = sharedPreferences.getString(key, "");
List<String> data = gson.fromJson(group, List.class);
return data;
}
public static void savePreference(Context ctx, String key, String value) {
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
if(!value.isEmpty()) editor.putString(key, value);
else editor.putString(key, Environment.getExternalStorageDirectory().getAbsolutePath()); // Default
// Commit the edits!
editor.apply();
}
/**
* Sets a long preference value.
*
* @param context the context
* @param keyId the key id
* @param value the value
*/
@SuppressLint("CommitPrefEdits")
public static void setLong(Context context, int keyId, long value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putLong(getKey(context, keyId), value);
ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor);
}
/**
* Function to get saved degree
*
* @return Quibla degree from north
*/
public static int getQuibla(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences
(MAIN_CONFIG, Context.MODE_PRIVATE);
int degree = sharedPreferences.getInt(QUIBLA_DEGREE, -1);
return degree;
}
static SharedPreferences obtainSharedPreferences(Context context) {
return context.getSharedPreferences(MAPBOX_SHARED_PREFERENCES, Context.MODE_PRIVATE);
}
private boolean getPrefBoolean(Context context, String key) {
SharedPreferences prefs =
context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return prefs.getBoolean(key, false);
}
protected DrawableCache(final Context context, final String name) {
this.name = name;
this.prefs = context.getSharedPreferences("cache_" + name, Context.MODE_PRIVATE);
this.keys = this.prefs.getStringSet("keys", new HashSet<>());
this.cachePath = context.getCacheDir().getPath() + "/";
}
public static long getLastUpdateTimeMillis(Context context) {
SharedPreferences sp = context.getSharedPreferences(Constants.APP_SETTINGS_NAME,
Context.MODE_PRIVATE);
return sp.getLong(Constants.LAST_UPDATE_TIME_IN_MS, 0);
}
public static void setCustomTheme(Context context, int theme) {
SharedPreferences shp = context.getSharedPreferences(MY_SHP_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shp.edit();
editor.putInt(THEME_KEY, theme);
editor.apply();
}
public static int getScId(Context context){
SharedPreferences userPreferences = context.getSharedPreferences(Constants.SHAREPREFER_UERINFO_NAME, Context.MODE_PRIVATE);
return userPreferences.getInt("scId", 0);
}
static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
}
static SharedPreferences getPreferences(Context context) {
return context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
}
/** Returns the Omaha SharedPreferences. */
static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(PREF_PACKAGE, Context.MODE_PRIVATE);
}
public static void remove(Context context, String key)
{
SharedPreferences settings = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.remove(key).commit();
}