2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package android.preference;
19 import android.app.Activity;
20 import android.content.Context;
21 import android.content.DialogInterface;
22 import android.content.Intent;
23 import android.content.SharedPreferences;
24 import android.content.pm.ActivityInfo;
25 import android.content.pm.PackageManager;
26 import android.content.pm.ResolveInfo;
27 import android.content.pm.PackageManager.NameNotFoundException;
28 import android.content.res.XmlResourceParser;
29 import android.os.Bundle;
30 import android.util.Log;
32 import java.util.ArrayList;
33 import java.util.HashSet;
34 import java.util.List;
37 * Used to help create {@link Preference} hierarchies
38 * from activities or XML.
40 * In most cases, clients should use
41 * {@link PreferenceActivity#addPreferencesFromIntent} or
42 * {@link PreferenceActivity#addPreferencesFromResource(int)}.
44 * @see PreferenceActivity
46 public class PreferenceManager {
48 private static final String TAG = "PreferenceManager";
51 * The Activity meta-data key for its XML preference hierarchy.
53 public static final String METADATA_KEY_PREFERENCES = "android.preference";
55 public static final String KEY_HAS_SET_DEFAULT_VALUES = "_has_set_default_values";
60 private Activity mActivity;
63 * Fragment that owns this instance.
65 private PreferenceFragment mFragment;
68 * The context to use. This should always be set.
72 private Context mContext;
75 * The counter for unique IDs.
77 private long mNextId = 0;
80 * The counter for unique request codes.
82 private int mNextRequestCode;
85 * Cached shared preferences.
87 private SharedPreferences mSharedPreferences;
90 * If in no-commit mode, the shared editor to give out (which will be
91 * committed when exiting no-commit mode).
93 private SharedPreferences.Editor mEditor;
96 * Blocks commits from happening on the shared editor. This is used when
97 * inflating the hierarchy. Do not set this directly, use {@link #setNoCommit(boolean)}
99 private boolean mNoCommit;
102 * The SharedPreferences name that will be used for all {@link Preference}s
103 * managed by this instance.
105 private String mSharedPreferencesName;
108 * The SharedPreferences mode that will be used for all {@link Preference}s
109 * managed by this instance.
111 private int mSharedPreferencesMode;
114 * The {@link PreferenceScreen} at the root of the preference hierarchy.
116 private PreferenceScreen mPreferenceScreen;
119 * List of activity result listeners.
121 private List<OnActivityResultListener> mActivityResultListeners;
124 * List of activity stop listeners.
126 private List<OnActivityStopListener> mActivityStopListeners;
129 * List of activity destroy listeners.
131 private List<OnActivityDestroyListener> mActivityDestroyListeners;
134 * List of dialogs that should be dismissed when we receive onNewIntent in
135 * our PreferenceActivity.
137 private List<DialogInterface> mPreferencesScreens;
139 private OnPreferenceTreeClickListener mOnPreferenceTreeClickListener;
141 PreferenceManager(Activity activity, int firstRequestCode) {
142 mActivity = activity;
143 mNextRequestCode = firstRequestCode;
149 * This constructor should ONLY be used when getting default values from
150 * an XML preference hierarchy.
152 * The {@link PreferenceManager#PreferenceManager(Activity)}
153 * should be used ANY time a preference will be displayed, since some preference
154 * types need an Activity for managed queries.
156 private PreferenceManager(Context context) {
160 private void init(Context context) {
163 setSharedPreferencesName(getDefaultSharedPreferencesName(context));
167 * Sets the owning preference fragment
169 void setFragment(PreferenceFragment fragment) {
170 mFragment = fragment;
174 * Returns the owning preference fragment, if any.
176 PreferenceFragment getFragment() {
181 * Returns a list of {@link Activity} (indirectly) that match a given
184 * @param queryIntent The Intent to match.
185 * @return The list of {@link ResolveInfo} that point to the matched
188 private List<ResolveInfo> queryIntentActivities(Intent queryIntent) {
189 return mContext.getPackageManager().queryIntentActivities(queryIntent,
190 PackageManager.GET_META_DATA);
194 * Inflates a preference hierarchy from the preference hierarchies of
195 * {@link Activity Activities} that match the given {@link Intent}. An
196 * {@link Activity} defines its preference hierarchy with meta-data using
197 * the {@link #METADATA_KEY_PREFERENCES} key.
199 * If a preference hierarchy is given, the new preference hierarchies will
202 * @param queryIntent The intent to match activities.
203 * @param rootPreferences Optional existing hierarchy to merge the new
205 * @return The root hierarchy (if one was not provided, the new hierarchy's
208 PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {
209 final List<ResolveInfo> activities = queryIntentActivities(queryIntent);
210 final HashSet<String> inflatedRes = new HashSet<String>();
212 for (int i = activities.size() - 1; i >= 0; i--) {
213 final ActivityInfo activityInfo = activities.get(i).activityInfo;
214 final Bundle metaData = activityInfo.metaData;
216 if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {
220 // Need to concat the package with res ID since the same res ID
221 // can be re-used across contexts
222 final String uniqueResId = activityInfo.packageName + ":"
223 + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);
225 if (!inflatedRes.contains(uniqueResId)) {
226 inflatedRes.add(uniqueResId);
228 final Context context;
230 context = mContext.createPackageContext(activityInfo.packageName, 0);
231 } catch (NameNotFoundException e) {
232 Log.w(TAG, "Could not create context for " + activityInfo.packageName + ": "
233 + Log.getStackTraceString(e));
237 final PreferenceInflater inflater = new PreferenceInflater(context, this);
238 final XmlResourceParser parser = activityInfo.loadXmlMetaData(context
239 .getPackageManager(), METADATA_KEY_PREFERENCES);
240 rootPreferences = (PreferenceScreen) inflater
241 .inflate(parser, rootPreferences, true);
246 rootPreferences.onAttachedToHierarchy(this);
248 return rootPreferences;
252 * Inflates a preference hierarchy from XML. If a preference hierarchy is
253 * given, the new preference hierarchies will be merged in.
255 * @param context The context of the resource.
256 * @param resId The resource ID of the XML to inflate.
257 * @param rootPreferences Optional existing hierarchy to merge the new
259 * @return The root hierarchy (if one was not provided, the new hierarchy's
263 public PreferenceScreen inflateFromResource(Context context, int resId,
264 PreferenceScreen rootPreferences) {
268 final PreferenceInflater inflater = new PreferenceInflater(context, this);
269 rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);
270 rootPreferences.onAttachedToHierarchy(this);
275 return rootPreferences;
278 public PreferenceScreen createPreferenceScreen(Context context) {
279 final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);
280 preferenceScreen.onAttachedToHierarchy(this);
281 return preferenceScreen;
285 * Called by a preference to get a unique ID in its hierarchy.
287 * @return A unique ID.
290 synchronized (this) {
296 * Returns the current name of the SharedPreferences file that preferences managed by
299 * @return The name that can be passed to {@link Context#getSharedPreferences(String, int)}.
300 * @see Context#getSharedPreferences(String, int)
302 public String getSharedPreferencesName() {
303 return mSharedPreferencesName;
307 * Sets the name of the SharedPreferences file that preferences managed by this
310 * @param sharedPreferencesName The name of the SharedPreferences file.
311 * @see Context#getSharedPreferences(String, int)
313 public void setSharedPreferencesName(String sharedPreferencesName) {
314 mSharedPreferencesName = sharedPreferencesName;
315 mSharedPreferences = null;
319 * Returns the current mode of the SharedPreferences file that preferences managed by
322 * @return The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.
323 * @see Context#getSharedPreferences(String, int)
325 public int getSharedPreferencesMode() {
326 return mSharedPreferencesMode;
330 * Sets the mode of the SharedPreferences file that preferences managed by this
333 * @param sharedPreferencesMode The mode of the SharedPreferences file.
334 * @see Context#getSharedPreferences(String, int)
336 public void setSharedPreferencesMode(int sharedPreferencesMode) {
337 mSharedPreferencesMode = sharedPreferencesMode;
338 mSharedPreferences = null;
342 * Gets a SharedPreferences instance that preferences managed by this will
345 * @return A SharedPreferences instance pointing to the file that contains
346 * the values of preferences that are managed by this.
348 public SharedPreferences getSharedPreferences() {
349 if (mSharedPreferences == null) {
350 mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName,
351 mSharedPreferencesMode);
354 return mSharedPreferences;
358 * Gets a SharedPreferences instance that points to the default file that is
359 * used by the preference framework in the given context.
361 * @param context The context of the preferences whose values are wanted.
362 * @return A SharedPreferences instance that can be used to retrieve and
363 * listen to values of the preferences.
365 public static SharedPreferences getDefaultSharedPreferences(Context context) {
366 return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
367 getDefaultSharedPreferencesMode());
370 private static String getDefaultSharedPreferencesName(Context context) {
371 return context.getPackageName() + "_preferences";
374 private static int getDefaultSharedPreferencesMode() {
375 return Context.MODE_PRIVATE;
379 * Returns the root of the preference hierarchy managed by this class.
381 * @return The {@link PreferenceScreen} object that is at the root of the hierarchy.
383 PreferenceScreen getPreferenceScreen() {
384 return mPreferenceScreen;
388 * Sets the root of the preference hierarchy.
390 * @param preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
391 * @return Whether the {@link PreferenceScreen} given is different than the previous.
393 boolean setPreferences(PreferenceScreen preferenceScreen) {
394 if (preferenceScreen != mPreferenceScreen) {
395 mPreferenceScreen = preferenceScreen;
403 * Finds a {@link Preference} based on its key.
405 * @param key The key of the preference to retrieve.
406 * @return The {@link Preference} with the key, or null.
407 * @see PreferenceGroup#findPreference(CharSequence)
409 public Preference findPreference(CharSequence key) {
410 if (mPreferenceScreen == null) {
414 return mPreferenceScreen.findPreference(key);
418 * Sets the default values from an XML preference file by reading the values defined
419 * by each {@link Preference} item's {@code android:defaultValue} attribute. This should
420 * be called by the application's main activity.
423 * @param context The context of the shared preferences.
424 * @param resId The resource ID of the preference XML file.
425 * @param readAgain Whether to re-read the default values.
426 * If false, this method sets the default values only if this
427 * method has never been called in the past (or if the
428 * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared
429 * preferences file is false). To attempt to set the default values again
430 * bypassing this check, set {@code readAgain} to true.
432 * Note: this will NOT reset preferences back to their default
433 * values. For that functionality, use
434 * {@link PreferenceManager#getDefaultSharedPreferences(Context)}
435 * and clear it followed by a call to this method with this
436 * parameter set to true.
438 public static void setDefaultValues(Context context, int resId, boolean readAgain) {
440 // Use the default shared preferences name and mode
441 setDefaultValues(context, getDefaultSharedPreferencesName(context),
442 getDefaultSharedPreferencesMode(), resId, readAgain);
446 * Similar to {@link #setDefaultValues(Context, int, boolean)} but allows
447 * the client to provide the filename and mode of the shared preferences
450 * @param context The context of the shared preferences.
451 * @param sharedPreferencesName A custom name for the shared preferences file.
452 * @param sharedPreferencesMode The file creation mode for the shared preferences file, such
453 * as {@link android.content.Context#MODE_PRIVATE} or {@link
454 * android.content.Context#MODE_PRIVATE}
455 * @param resId The resource ID of the preference XML file.
456 * @param readAgain Whether to re-read the default values.
457 * If false, this method will set the default values only if this
458 * method has never been called in the past (or if the
459 * {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared
460 * preferences file is false). To attempt to set the default values again
461 * bypassing this check, set {@code readAgain} to true.
463 * Note: this will NOT reset preferences back to their default
464 * values. For that functionality, use
465 * {@link PreferenceManager#getDefaultSharedPreferences(Context)}
466 * and clear it followed by a call to this method with this
467 * parameter set to true.
469 * @see #setDefaultValues(Context, int, boolean)
470 * @see #setSharedPreferencesName(String)
471 * @see #setSharedPreferencesMode(int)
473 public static void setDefaultValues(Context context, String sharedPreferencesName,
474 int sharedPreferencesMode, int resId, boolean readAgain) {
475 final SharedPreferences defaultValueSp = context.getSharedPreferences(
476 KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);
478 if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {
479 final PreferenceManager pm = new PreferenceManager(context);
480 pm.setSharedPreferencesName(sharedPreferencesName);
481 pm.setSharedPreferencesMode(sharedPreferencesMode);
482 pm.inflateFromResource(context, resId, null);
484 SharedPreferences.Editor editor =
485 defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true);
488 } catch (AbstractMethodError unused) {
489 // The app injected its own pre-Gingerbread
490 // SharedPreferences.Editor implementation without
498 * Returns an editor to use when modifying the shared preferences.
500 * Do NOT commit unless {@link #shouldCommit()} returns true.
502 * @return An editor to use to write to shared preferences.
503 * @see #shouldCommit()
505 SharedPreferences.Editor getEditor() {
508 if (mEditor == null) {
509 mEditor = getSharedPreferences().edit();
514 return getSharedPreferences().edit();
519 * Whether it is the client's responsibility to commit on the
520 * {@link #getEditor()}. This will return false in cases where the writes
521 * should be batched, for example when inflating preferences from XML.
523 * @return Whether the client should commit.
525 boolean shouldCommit() {
529 private void setNoCommit(boolean noCommit) {
530 if (!noCommit && mEditor != null) {
533 } catch (AbstractMethodError unused) {
534 // The app injected its own pre-Gingerbread
535 // SharedPreferences.Editor implementation without
540 mNoCommit = noCommit;
544 * Returns the activity that shows the preferences. This is useful for doing
545 * managed queries, but in most cases the use of {@link #getContext()} is
548 * This will return null if this class was instantiated with a Context
549 * instead of Activity. For example, when setting the default values.
551 * @return The activity that shows the preferences.
554 Activity getActivity() {
559 * Returns the context. This is preferred over {@link #getActivity()} when
562 * @return The context.
564 Context getContext() {
569 * Registers a listener.
571 * @see OnActivityResultListener
573 void registerOnActivityResultListener(OnActivityResultListener listener) {
574 synchronized (this) {
575 if (mActivityResultListeners == null) {
576 mActivityResultListeners = new ArrayList<OnActivityResultListener>();
579 if (!mActivityResultListeners.contains(listener)) {
580 mActivityResultListeners.add(listener);
586 * Unregisters a listener.
588 * @see OnActivityResultListener
590 void unregisterOnActivityResultListener(OnActivityResultListener listener) {
591 synchronized (this) {
592 if (mActivityResultListeners != null) {
593 mActivityResultListeners.remove(listener);
599 * Called by the {@link PreferenceManager} to dispatch a subactivity result.
601 void dispatchActivityResult(int requestCode, int resultCode, Intent data) {
602 List<OnActivityResultListener> list;
604 synchronized (this) {
605 if (mActivityResultListeners == null) return;
606 list = new ArrayList<OnActivityResultListener>(mActivityResultListeners);
609 final int N = list.size();
610 for (int i = 0; i < N; i++) {
611 if (list.get(i).onActivityResult(requestCode, resultCode, data)) {
618 * Registers a listener.
620 * @see OnActivityStopListener
622 void registerOnActivityStopListener(OnActivityStopListener listener) {
623 synchronized (this) {
624 if (mActivityStopListeners == null) {
625 mActivityStopListeners = new ArrayList<OnActivityStopListener>();
628 if (!mActivityStopListeners.contains(listener)) {
629 mActivityStopListeners.add(listener);
635 * Unregisters a listener.
637 * @see OnActivityStopListener
639 void unregisterOnActivityStopListener(OnActivityStopListener listener) {
640 synchronized (this) {
641 if (mActivityStopListeners != null) {
642 mActivityStopListeners.remove(listener);
648 * Called by the {@link PreferenceManager} to dispatch the activity stop
651 void dispatchActivityStop() {
652 List<OnActivityStopListener> list;
654 synchronized (this) {
655 if (mActivityStopListeners == null) return;
656 list = new ArrayList<OnActivityStopListener>(mActivityStopListeners);
659 final int N = list.size();
660 for (int i = 0; i < N; i++) {
661 list.get(i).onActivityStop();
666 * Registers a listener.
668 * @see OnActivityDestroyListener
670 void registerOnActivityDestroyListener(OnActivityDestroyListener listener) {
671 synchronized (this) {
672 if (mActivityDestroyListeners == null) {
673 mActivityDestroyListeners = new ArrayList<OnActivityDestroyListener>();
676 if (!mActivityDestroyListeners.contains(listener)) {
677 mActivityDestroyListeners.add(listener);
683 * Unregisters a listener.
685 * @see OnActivityDestroyListener
687 void unregisterOnActivityDestroyListener(OnActivityDestroyListener listener) {
688 synchronized (this) {
689 if (mActivityDestroyListeners != null) {
690 mActivityDestroyListeners.remove(listener);
696 * Called by the {@link PreferenceManager} to dispatch the activity destroy
699 void dispatchActivityDestroy() {
700 List<OnActivityDestroyListener> list = null;
702 synchronized (this) {
703 if (mActivityDestroyListeners != null) {
704 list = new ArrayList<OnActivityDestroyListener>(mActivityDestroyListeners);
709 final int N = list.size();
710 for (int i = 0; i < N; i++) {
711 list.get(i).onActivityDestroy();
715 // Dismiss any PreferenceScreens still showing
720 * Returns a request code that is unique for the activity. Each subsequent
721 * call to this method should return another unique request code.
723 * @return A unique request code that will never be used by anyone other
724 * than the caller of this method.
726 int getNextRequestCode() {
727 synchronized (this) {
728 return mNextRequestCode++;
732 void addPreferencesScreen(DialogInterface screen) {
733 synchronized (this) {
735 if (mPreferencesScreens == null) {
736 mPreferencesScreens = new ArrayList<DialogInterface>();
739 mPreferencesScreens.add(screen);
743 void removePreferencesScreen(DialogInterface screen) {
744 synchronized (this) {
746 if (mPreferencesScreens == null) {
750 mPreferencesScreens.remove(screen);
755 * Called by {@link PreferenceActivity} to dispatch the new Intent event.
757 * @param intent The new Intent.
759 void dispatchNewIntent(Intent intent) {
763 private void dismissAllScreens() {
764 // Remove any of the previously shown preferences screens
765 ArrayList<DialogInterface> screensToDismiss;
767 synchronized (this) {
769 if (mPreferencesScreens == null) {
773 screensToDismiss = new ArrayList<DialogInterface>(mPreferencesScreens);
774 mPreferencesScreens.clear();
777 for (int i = screensToDismiss.size() - 1; i >= 0; i--) {
778 screensToDismiss.get(i).dismiss();
783 * Sets the callback to be invoked when a {@link Preference} in the
784 * hierarchy rooted at this {@link PreferenceManager} is clicked.
786 * @param listener The callback to be invoked.
788 void setOnPreferenceTreeClickListener(OnPreferenceTreeClickListener listener) {
789 mOnPreferenceTreeClickListener = listener;
792 OnPreferenceTreeClickListener getOnPreferenceTreeClickListener() {
793 return mOnPreferenceTreeClickListener;
797 * Interface definition for a callback to be invoked when a
798 * {@link Preference} in the hierarchy rooted at this {@link PreferenceScreen} is
801 interface OnPreferenceTreeClickListener {
803 * Called when a preference in the tree rooted at this
804 * {@link PreferenceScreen} has been clicked.
806 * @param preferenceScreen The {@link PreferenceScreen} that the
807 * preference is located in.
808 * @param preference The preference that was clicked.
809 * @return Whether the click was handled.
811 boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference);
815 * Interface definition for a class that will be called when the container's activity
816 * receives an activity result.
818 public interface OnActivityResultListener {
821 * See Activity's onActivityResult.
823 * @return Whether the request code was handled (in which case
824 * subsequent listeners will not be called.
826 boolean onActivityResult(int requestCode, int resultCode, Intent data);
830 * Interface definition for a class that will be called when the container's activity
833 public interface OnActivityStopListener {
836 * See Activity's onStop.
838 void onActivityStop();
842 * Interface definition for a class that will be called when the container's activity
845 public interface OnActivityDestroyListener {
848 * See Activity's onDestroy.
850 void onActivityDestroy();