下面列出了android.content.SharedPreferences#registerOnSharedPreferenceChangeListener ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void onResume() {
super.onResume();
checkPermissions(null);
// Listen for preference changes
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
// Listen for interactive state changes
IntentFilter ifInteractive = new IntentFilter();
ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(interactiveStateReceiver, ifInteractive);
// Listen for connectivity updates
IntentFilter ifConnectivity = new IntentFilter();
ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityChangedReceiver, ifConnectivity);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
processSetTheme(this, Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction()));
super.onCreate(savedInstanceState);
final String uuid = getIntent().getStringExtra("UUID");
if (uuid != null) {
final SharedPreferences uuidSp = getSharedPreferences(uuid, MODE_PRIVATE);
uuidSp.registerOnSharedPreferenceChangeListener(this);
}
if (Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())) {
doCreateShortCut();
} else {
doShowFolder();
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Retrieve the Earthquake View Model for the parent Activity.
earthquakeViewModel = ViewModelProviders.of(getActivity())
.get(EarthquakeViewModel.class);
// Get the data from the View Model, and observe any changes.
earthquakeViewModel.getEarthquakes()
.observe(this, new Observer<List<Earthquake>>() {
@Override
public void onChanged(@Nullable List<Earthquake> earthquakes) {
// When the View Model changes, update the List
if (earthquakes != null)
setEarthquakes(earthquakes);
}
});
// Register an OnSharedPreferenceChangeListener
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
prefs.registerOnSharedPreferenceChangeListener(mPrefListener);
}
private void setupSharedPreferences() {
// Get all of the values from shared preferences to set it up
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mVisualizerView.setShowBass(sharedPreferences.getBoolean(getString(R.string.pref_show_bass_key),
getResources().getBoolean(R.bool.pref_show_bass_default)));
mVisualizerView.setShowMid(sharedPreferences.getBoolean(getString(R.string.pref_show_mid_range_key),
getResources().getBoolean(R.bool.pref_show_mid_range_default)));
mVisualizerView.setShowTreble(sharedPreferences.getBoolean(getString(R.string.pref_show_treble_key),
getResources().getBoolean(R.bool.pref_show_treble_default)));
mVisualizerView.setMinSizeScale(Float.parseFloat(
sharedPreferences.getString(getString(R.string.pref_size_key),
getString(R.string.pref_size_default))));
loadColorFromPreferences(sharedPreferences);
// Register the listener
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Retrieve the Earthquake View Model for the parent Activity.
earthquakeViewModel = ViewModelProviders.of(getActivity())
.get(EarthquakeViewModel.class);
// Get the data from the View Model, and observe any changes.
earthquakeViewModel.getEarthquakes()
.observe(this, new Observer<List<Earthquake>>() {
@Override
public void onChanged(@Nullable List<Earthquake> earthquakes) {
// When the View Model changes, update the List
if (earthquakes != null)
setEarthquakes(earthquakes);
}
});
// Register an OnSharedPreferenceChangeListener
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
prefs.registerOnSharedPreferenceChangeListener(mPrefListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Get the views **/
mWaterCountDisplay = (TextView) findViewById(R.id.tv_water_count);
mChargingCountDisplay = (TextView) findViewById(R.id.tv_charging_reminder_count);
mChargingImageView = (ImageView) findViewById(R.id.iv_power_increment);
/** Set the original values in the UI **/
updateWaterCount();
updateChargingReminderCount();
/** Setup the shared preference listener **/
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Retrieve the Earthquake View Model for the parent Activity.
earthquakeViewModel = ViewModelProviders.of(getActivity())
.get(EarthquakeViewModel.class);
// Get the data from the View Model, and observe any changes.
earthquakeViewModel.getEarthquakes()
.observe(this, new Observer<List<Earthquake>>() {
@Override
public void onChanged(@Nullable List<Earthquake> earthquakes) {
// When the View Model changes, update the List
if (earthquakes != null)
setEarthquakes(earthquakes);
}
});
// Register an OnSharedPreferenceChangeListener
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
prefs.registerOnSharedPreferenceChangeListener(mPrefListener);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Retrieve the Earthquake View Model for the parent Activity.
earthquakeViewModel = ViewModelProviders.of(getActivity())
.get(EarthquakeViewModel.class);
// Get the data from the View Model, and observe any changes.
earthquakeViewModel.getEarthquakes()
.observe(this, new Observer<List<Earthquake>>() {
@Override
public void onChanged(@Nullable List<Earthquake> earthquakes) {
// When the View Model changes, update the List
if (earthquakes != null)
setEarthquakes(earthquakes);
}
});
// Register an OnSharedPreferenceChangeListener
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
prefs.registerOnSharedPreferenceChangeListener(mPrefListener);
}
@Override
public void onCreate() {
super.onCreate();
mRecommendedThreshold = Float.parseFloat(
getString(R.string.spellchecker_recommended_threshold_value));
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(prefs, PREF_USE_CONTACTS_KEY);
}
private void initializeSharedPreferences(SharedPreferences sharedPreferences) {
try {
isEnabled.set(sharedPreferences.getBoolean(MAPBOX_PREF_ENABLE_CRASH_REPORTER, true));
} catch (Exception ex) {
// In case of a ClassCastException
Log.e(TAG, ex.toString());
}
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
private void xmlImport(InputStream in) throws IOException, SAXException, ParserConfigurationException {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.unregisterOnSharedPreferenceChangeListener(this);
prefs.edit().putBoolean("enabled", false).apply();
ServiceSinkhole.stop("import", this, false);
XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
XmlImportHandler handler = new XmlImportHandler(this);
reader.setContentHandler(handler);
reader.parse(new InputSource(in));
xmlImport(handler.application, prefs);
xmlImport(handler.wifi, getSharedPreferences("wifi", Context.MODE_PRIVATE));
xmlImport(handler.mobile, getSharedPreferences("other", Context.MODE_PRIVATE));
xmlImport(handler.screen_wifi, getSharedPreferences("screen_wifi", Context.MODE_PRIVATE));
xmlImport(handler.screen_other, getSharedPreferences("screen_other", Context.MODE_PRIVATE));
xmlImport(handler.roaming, getSharedPreferences("roaming", Context.MODE_PRIVATE));
xmlImport(handler.lockdown, getSharedPreferences("lockdown", Context.MODE_PRIVATE));
xmlImport(handler.apply, getSharedPreferences("apply", Context.MODE_PRIVATE));
xmlImport(handler.notify, getSharedPreferences("notify", Context.MODE_PRIVATE));
xmlImport(handler.blocklist, getSharedPreferences(PREF_BLOCKLIST, Context.MODE_PRIVATE));
// Reload blocklist
AppBlocklistController.getInstance(this).loadSettings(this);
// Upgrade imported settings
ReceiverAutostart.upgrade(true, this);
DatabaseHelper.clearCache();
// Refresh UI
prefs.edit().putBoolean("imported", true).apply();
prefs.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onCreate() {
super.onCreate();
mRecommendedThreshold = Float.parseFloat(
getString(R.string.spellchecker_recommended_threshold_value));
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(prefs, PREF_USE_CONTACTS_KEY);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.settings_activity_title);
setContentView(R.layout.activity_container);
Toolbar toolbar = findViewById(R.id.container_toolbar);
setSupportActionBar(toolbar);
ViewStub stub = findViewById(R.id.container_stub);
stub.inflate();
Intent callingIntent = getIntent();
byte[] keyMaterial = callingIntent.getByteArrayExtra(Constants.EXTRA_SETTINGS_ENCRYPTION_KEY);
if (keyMaterial != null && keyMaterial.length > 0)
encryptionKey = EncryptionHelper.generateSymmetricKey(keyMaterial);
if (savedInstanceState != null) {
encryptionChanged = savedInstanceState.getBoolean(Constants.EXTRA_SETTINGS_ENCRYPTION_CHANGED, false);
byte[] encKey = savedInstanceState.getByteArray(Constants.EXTRA_SETTINGS_ENCRYPTION_KEY);
if (encKey != null) {
encryptionKey = EncryptionHelper.generateSymmetricKey(encKey);
}
}
fragment = new SettingsFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container_content, fragment)
.commit();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sharedPref.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG,"created");
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
preferencesListener = new PreferencesListener(getActivity(), prefs, this);
prefs.registerOnSharedPreferenceChangeListener(preferencesListener);
}
/**
* Registers SecureStorageChangeListener to listen to any changes in SecureStorage
*
* @param context Context is used internally
* @param listener Provided listener with given behaviour from the developer that will be registered
*/
public static void registerOnSharedPreferenceChangeListener(@NonNull Context context,
@NonNull SharedPreferences.OnSharedPreferenceChangeListener listener) {
Context applicationContext = context.getApplicationContext();
SharedPreferences preferences = applicationContext
.getSharedPreferences(KEY_SHARED_PREFERENCES_NAME, MODE_PRIVATE);
preferences.registerOnSharedPreferenceChangeListener(listener);
}
private void setupSharedPreferences() {
// Get all of the values from shared preferences to set it up
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mVisualizerView.setShowBass(sharedPreferences.getBoolean(getString(R.string.pref_show_bass_key),
getResources().getBoolean(R.bool.pref_show_bass_default)));
mVisualizerView.setShowMid(sharedPreferences.getBoolean(getString(R.string.pref_show_mid_range_key),
getResources().getBoolean(R.bool.pref_show_mid_range_default)));
mVisualizerView.setShowTreble(sharedPreferences.getBoolean(getString(R.string.pref_show_treble_key),
getResources().getBoolean(R.bool.pref_show_treble_default)));
mVisualizerView.setMinSizeScale(1);
mVisualizerView.setColor(sharedPreferences.getString(getString(R.string.pref_color_key),
getString(R.string.pref_color_red_value)));
// Register the listener
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Register an OnSharedPreferenceChangeListener
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
prefs.registerOnSharedPreferenceChangeListener(mPListener);
}
@Override
protected void onResume() {
super.onResume();
StatService.onResume(this);//统计activity页面
SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
String show_day = sharedPreferences.getString("pref_setting_ad_day_key","选择弹出时间") + "天";
lp_ad_day.setSummary(show_day);
String show_count = sharedPreferences.getString("pref_setting_ad_count_key","选择弹出次数") + "次";
lp_ad_count.setSummary(show_count);
// Set up a listener whenever a key changes
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onCreate() {
Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));
startForeground(NOTIFY_WAITING, getWaitingNotification());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (jni_context != 0) {
Log.w(TAG, "Create with context=" + jni_context);
jni_stop(jni_context);
synchronized (jni_lock) {
jni_done(jni_context);
jni_context = 0;
}
}
// Native init
jni_context = jni_init(Build.VERSION.SDK_INT);
Log.i(TAG, "Created context=" + jni_context);
boolean pcap = prefs.getBoolean("pcap", false);
setPcap(pcap, this);
prefs.registerOnSharedPreferenceChangeListener(this);
Util.setTheme(this);
super.onCreate();
HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command", Process.THREAD_PRIORITY_FOREGROUND);
HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log", Process.THREAD_PRIORITY_BACKGROUND);
HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats", Process.THREAD_PRIORITY_BACKGROUND);
commandThread.start();
logThread.start();
statsThread.start();
commandLooper = commandThread.getLooper();
logLooper = logThread.getLooper();
statsLooper = statsThread.getLooper();
commandHandler = new CommandHandler(commandLooper);
logHandler = new LogHandler(logLooper);
statsHandler = new StatsHandler(statsLooper);
// Listen for user switches
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
IntentFilter ifUser = new IntentFilter();
ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
registerReceiver(userReceiver, ifUser);
registeredUser = true;
}
// Listen for idle mode state changes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
IntentFilter ifIdle = new IntentFilter();
ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
registerReceiver(idleStateReceiver, ifIdle);
registeredIdleState = true;
}
// Listen for added/removed applications
IntentFilter ifPackage = new IntentFilter();
ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
ifPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
ifPackage.addDataScheme("package");
registerReceiver(packageChangedReceiver, ifPackage);
registeredPackageChanged = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
try {
listenNetworkChanges();
} catch (Throwable ex) {
Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
listenConnectivityChanges();
}
else
listenConnectivityChanges();
// Monitor networks
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cm.registerNetworkCallback(
new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(),
networkMonitorCallback);
// Setup house holding
Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
alarmIntent.setAction(ACTION_HOUSE_HOLDING);
PendingIntent pi;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
pi = PendingIntent.getForegroundService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
else
pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000, AlarmManager.INTERVAL_HALF_DAY, pi);
}
private CustomSettings(Launcher launcher) {
SharedPreferences prefs = Utilities.getPrefs(launcher);
prefs.registerOnSharedPreferenceChangeListener(this);
mLauncher = launcher;
}