下面列出了android.content.SharedPreferences#getBoolean ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.d("dtube","pref changed "+key);
switch (key){
case "dark_mode":
if (pref!=null)
pref.unregisterOnSharedPreferenceChangeListener(this);
Preferences.darkMode = sharedPreferences.getBoolean("dark_mode", false);
MainActivity.changedDarkMode = true;
if (uiActivity!=null)
uiActivity.finish();
finish();
startActivity(new Intent(PreferencesActivity.this, PreferencesActivity.class));
break;
default:
break;
}
}
@Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
if (renderer != null) {
if (visible) {
final SharedPreferences pref = getSharedPreferences(
LWApplication.OPTIONS_PREF, MODE_PRIVATE
);
allowSlide = pref.getBoolean(LWApplication.SLIDE_WALLPAPER_KEY, false);
glSurfaceView.onResume();
startPlayer();
} else {
stopPlayer();
glSurfaceView.onPause();
// Prevent useless renderer calculating.
allowSlide = false;
}
}
}
private void onExit() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
boolean setup_reminder = prefs.getBoolean("setup_reminder", true);
boolean hasPermissions = hasPermission(Manifest.permission.READ_CONTACTS);
Boolean isIgnoring = Helper.isIgnoringOptimizations(getContext());
if (!setup_reminder ||
(hasPermissions && (isIgnoring == null || isIgnoring)))
super.finish();
else {
FragmentDialogStill fragment = new FragmentDialogStill();
fragment.setTargetFragment(this, ActivitySetup.REQUEST_STILL);
fragment.show(getParentFragmentManager(), "setup:still");
}
}
AdapterAccount(final Fragment parentFragment, boolean settings) {
this.parentFragment = parentFragment;
this.settings = settings;
this.context = parentFragment.getContext();
this.owner = parentFragment.getViewLifecycleOwner();
this.inflater = LayoutInflater.from(context);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean highlight_unread = prefs.getBoolean("highlight_unread", true);
this.colorUnread = Helper.resolveColor(context, highlight_unread ? R.attr.colorUnreadHighlight : android.R.attr.textColorPrimary);
this.textColorSecondary = Helper.resolveColor(context, android.R.attr.textColorSecondary);
this.DTF = Helper.getDateTimeInstance(context, DateFormat.SHORT, DateFormat.SHORT);
setHasStableIds(true);
owner.getLifecycle().addObserver(new LifecycleObserver() {
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroyed() {
Log.d(AdapterAccount.this + " parent destroyed");
AdapterAccount.this.parentFragment = null;
}
});
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
*
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object get(Context context, String key, Object defaultObject)
{
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
if (defaultObject instanceof String)
{
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer)
{
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean)
{
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float)
{
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long)
{
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
@Override
public void onReceive(final Context context, Intent intent) {
if (Objects.equals(intent.getAction(), "android.intent.action.BOOT_COMPLETED")) {
final SharedPreferences sharedPreferences = context.getSharedPreferences("data", MODE_PRIVATE);
if (sharedPreferences.getBoolean("initialized", false)) {
public_func.start_service(context, sharedPreferences.getBoolean("battery_monitoring_switch", false));
}
}
}
@Override
protected void onResume() {
SharedPreferences mSp = PreferenceManager.getDefaultSharedPreferences(this);
if (BaseMethod.isAccessibilitySettingsOn(this) && (mSp.getBoolean(Config.ROOT_OPEN_SERVICE, false) || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)) {
mBtnStart.setText(R.string.close_service);
} else {
mBtnStart.setText(R.string.go_start);
}
super.onResume();
}
public static String getSenderId(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean useCustom = preferences.getBoolean("server_use_custom", false);
if (useCustom) {
return preferences.getString("server_custom_sender_id", DEFAULT_SENDER_ID);
} else {
return DEFAULT_SENDER_ID;
}
}
/**
* 从文件中读取数据
*
* @param context
* @param key
* @param defValue
* @return
*/
public static Object getData(Context context, String key, Object defValue) {
try {
//利用java反射机制将XML文件自定义存储
Field field;
// 获取ContextWrapper对象中的mBase变量。该变量保存了ContextImpl对象
field = ContextWrapper.class.getDeclaredField("mBase");
field.setAccessible(true);
// 获取mBase变量
Object obj = field.get(context);
// 获取ContextImpl。mPreferencesDir变量,该变量保存了数据文件的保存路径
field = obj.getClass().getDeclaredField("mPreferencesDir");
field.setAccessible(true);
// 创建自定义路径
File file = new File(FILE_PATH);
// 修改mPreferencesDir变量的值
field.set(obj, file);
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;
} catch (Exception e) {
return defValue;
}
}
private static void start(Context context, Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean background_service = prefs.getBoolean("background_service", false);
if (background_service)
context.startService(intent);
else
ContextCompat.startForegroundService(context, intent);
}
public static Object get(String key, Object defaultObject) {
SharedPreferences sp = CommonApp.getInstance().getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
public static int isReceivingEnabled(Context context) {
SharedPreferences prefs = context.getSharedPreferences(PREF_FILE, Activity.MODE_PRIVATE);
int retval = prefs.getInt(PREF_RCVENABLED, -1);
if (retval == -1) { // Fetch legacy value
if (prefs.getBoolean(PREF_RCVENABLED_LEGACY, true))
return ComponentConstants.TEXT_RECEIVING_FOREGROUND; // Foreground
else
return ComponentConstants.TEXT_RECEIVING_OFF; // Off
}
return retval;
}
public static void setWindowDecorations(Activity activity, SharedPreferences options) {
if (!options.getBoolean(Keys.FULLSCREEN, false)) {
activity.getWindow().setStatusBarColor(options.getInt(Keys.STATUS_BAR_BACKGROUND, 0x22000000));
}
activity.getWindow().setNavigationBarColor(options.getInt(Keys.NAV_BAR_BACKGROUND, 0x22000000));
}
public static boolean getBoolean(@NonNull String key) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(App.getInstance());
return preferences.getAll().get(key) instanceof Boolean && preferences.getBoolean(key, false);
}
private void checkPurchases(List<Purchase> purchases) {
Log.i("IAB purchases=" + (purchases == null ? null : purchases.size()));
List<String> query = new ArrayList<>();
query.add(getSkuPro());
if (purchases != null) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
if (prefs.getBoolean("play_store", true)) {
long cached = prefs.getLong(getSkuPro() + ".cached", 0);
if (cached + MAX_SKU_CACHE_DURATION < new Date().getTime()) {
Log.i("IAB cache expired=" + new Date(cached));
editor.remove("pro");
} else
Log.i("IAB caching until=" + new Date(cached + MAX_SKU_CACHE_DURATION));
}
for (Purchase purchase : purchases)
try {
query.remove(purchase.getSku());
long time = purchase.getPurchaseTime();
Log.i("IAB SKU=" + purchase.getSku() +
" purchased=" + isPurchased(purchase) +
" valid=" + isPurchaseValid(purchase) +
" time=" + new Date(time));
//if (new Date().getTime() - purchase.getPurchaseTime() > 3 * 60 * 1000L) {
// consumePurchase(purchase);
// continue;
//}
for (IBillingListener listener : listeners)
if (isPurchaseValid(purchase))
listener.onPurchased(purchase.getSku());
else
listener.onPurchasePending(purchase.getSku());
if (isPurchased(purchase)) {
byte[] decodedKey = Base64.decode(getString(R.string.public_key), Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(publicKey);
sig.update(purchase.getOriginalJson().getBytes());
if (sig.verify(Base64.decode(purchase.getSignature(), Base64.DEFAULT))) {
Log.i("IAB valid signature");
if (getSkuPro().equals(purchase.getSku())) {
if (isPurchaseValid(purchase)) {
editor.putBoolean("pro", true);
editor.putLong(purchase.getSku() + ".cached", new Date().getTime());
}
if (!purchase.isAcknowledged())
acknowledgePurchase(purchase, 0);
}
} else {
Log.w("IAB invalid signature");
editor.putBoolean("pro", false);
reportError(null, "Invalid purchase");
}
}
} catch (Throwable ex) {
reportError(null, Log.formatThrowable(ex, false));
}
editor.apply();
WidgetUnified.updateData(this);
}
if (query.size() > 0)
querySkus(query);
}
private static boolean shouldSetThemeFromPreferences(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(NavigationConstants.NAVIGATION_VIEW_PREFERENCE_SET_THEME, false);
}
@Override
protected void onHandleIntent(Intent intent) {
String date;
Double lat=0d, lon=0d, altitude = null;
Float speed = null, direction = null;
Integer acc = null;
String message = intent.getStringExtra("message");
String phone = intent.getStringExtra("phone");
Pattern lat_lon = Pattern.compile("^lat:(-?\\d+\\.\\d+) lon:(-?\\d+\\.\\d+)");
Matcher m_lat_lon = lat_lon.matcher(message);
if (m_lat_lon.find()) {
lat = Double.valueOf(m_lat_lon.group(1)); //will be initialized, regexp checked in the receiver
lon = Double.valueOf(m_lat_lon.group(2));
}
Pattern alt = Pattern.compile("alt:(\\d+\\.?\\d*)");
Matcher m_alt = alt.matcher(message);
if (m_alt.find()) {
altitude = Double.valueOf(m_alt.group(1));
}
Pattern spd = Pattern.compile("vel:(\\d+\\.?\\d*)");
Matcher m_spd = spd.matcher(message);
if (m_spd.find()) {
speed = Float.valueOf(m_spd.group(1));
}
Pattern dir = Pattern.compile("az:(\\d+\\.?\\d*)");
Matcher m_dir = dir.matcher(message);
if (m_dir.find()) {
direction = Float.valueOf(m_dir.group(1));
}
Pattern ac = Pattern.compile("acc:(\\d+)");
Matcher m_acc = ac.matcher(message);
if (m_acc.find()) {
acc = Integer.valueOf(m_acc.group(1));
}
Pattern bat = Pattern.compile("bat:(\\d+)%");
Matcher bat_matcher = bat.matcher(message);
String bat_value = null;
if (bat_matcher.find()) {
bat_value = bat_matcher.group(1);
}
dBase baseConnect = new dBase(getApplicationContext());
SQLiteDatabase db = baseConnect.getWritableDatabase();
DateFormat df = new SimpleDateFormat("MMM d, HH:mm");
date = df.format(Calendar.getInstance().getTime());
MainActivity.write_to_hist(db, phone, lat, lon, acc, date, bat_value, altitude, speed, direction);
String name;
//get phone name for notification, if it exists
Cursor name_curs = db.query(dBase.PHONES_TABLE_OUT, new String[] {dBase.NAME_COL},
"phone = ?", new String[] {phone},
null, null, null);
name = (name_curs.moveToFirst()) ? (name_curs.getString(name_curs.getColumnIndex(dBase.NAME_COL))) : (phone);
name_curs.close();
db.close();
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (MainActivity.activityRunning && sPref.getBoolean("auto_map", false)) { //run map only in case of opened app and setting this
Intent start_map = new Intent(getApplicationContext(), MapsActivity.class);
start_map.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
start_map.putExtra("lat", lat);
start_map.putExtra("lon", lon);
start_map.putExtra("zoom", 15d);
if (acc != null) {
start_map.putExtra("accuracy", String.valueOf(acc) + getString(R.string.meters));
}
start_map.setAction("point");
startActivity(start_map);
} else {
Intent intentRes = new Intent(getApplicationContext(), HistoryActivity.class);
PendingIntent pendIntent = PendingIntent.getActivity(getApplicationContext(), 0, intentRes, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), MainActivity.COMMON_NOTIF_CHANNEL);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.message_with_coord))
.setContentText(getString(R.string.coords_received, name))
.setAutoCancel(true)
.setContentIntent(pendIntent);
Notification notification = builder.build();
NotificationManager nManage = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int id = sPref.getInt("notification_id", 2);
nManage.notify(id, notification);
sPref.edit().putInt("notification_id", id+1).commit(); //this is new thread (intent service)
}
}
private void notifyWeather() {
Context context = getContext();
//checking the last update and notify if it' the first of the day
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);
boolean displayNotifications = prefs.getBoolean(displayNotificationsKey,
Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));
if ( displayNotifications ) {
String lastNotificationKey = context.getString(R.string.pref_last_notification);
long lastSync = prefs.getLong(lastNotificationKey, 0);
if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) {
// Last sync was more than 1 day ago, let's send a notification with the weather.
String locationQuery = Utility.getPreferredLocation(context);
Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis());
// we'll query our contentProvider, as always
Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
int weatherId = cursor.getInt(INDEX_WEATHER_ID);
double high = cursor.getDouble(INDEX_MAX_TEMP);
double low = cursor.getDouble(INDEX_MIN_TEMP);
String desc = cursor.getString(INDEX_SHORT_DESC);
int iconId = Utility.getIconResourceForWeatherCondition(weatherId);
Resources resources = context.getResources();
Bitmap largeIcon = BitmapFactory.decodeResource(resources,
Utility.getArtResourceForWeatherCondition(weatherId));
String title = context.getString(R.string.app_name);
// Define the text of the forecast.
String contentText = String.format(context.getString(R.string.format_notification),
desc,
Utility.formatTemperature(context, high),
Utility.formatTemperature(context, low));
// NotificationCompatBuilder is a very convenient way to build backward-compatible
// notifications. Just throw in some data.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getContext())
.setColor(resources.getColor(R.color.sunshine_light_blue))
.setSmallIcon(iconId)
.setLargeIcon(largeIcon)
.setContentTitle(title)
.setContentText(contentText);
// Make something interesting happen when the user clicks on the notification.
// In this case, opening the app is sufficient.
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
// WEATHER_NOTIFICATION_ID allows you to update the notification later on.
mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build());
//refreshing last sync
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(lastNotificationKey, System.currentTimeMillis());
editor.commit();
}
cursor.close();
}
}
}
public static boolean getExpandedByDefaultPreference(Context context) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPrefs.getBoolean(
context.getText(R.string.pref_expanded_by_default).toString(), false);
}
/**
* Get whether or not the user has seen the what's new note.
*
* @param ctx the application context
* @return true if the user has seen the what's new note, false otherwise
*/
public static boolean getWhatsNew(@NonNull final Context ctx) {
final SharedPreferences pref = getPref(ctx);
return pref.getBoolean(WHATS_NEW, false);
}