FileDocCategorySizeDatePackage
PreferenceManager.javaAPI DocAndroid 1.5 API26212Wed May 06 22:41:56 BST 2009android.preference

PreferenceManager

public class PreferenceManager extends Object
Used to help create {@link Preference} hierarchies from activities or XML.

In most cases, clients should use {@link PreferenceActivity#addPreferencesFromIntent} or {@link PreferenceActivity#addPreferencesFromResource(int)}.

see
PreferenceActivity

Fields Summary
private static final String
TAG
public static final String
METADATA_KEY_PREFERENCES
The Activity meta-data key for its XML preference hierarchy.
public static final String
KEY_HAS_SET_DEFAULT_VALUES
private android.app.Activity
mActivity
private android.content.Context
mContext
The context to use. This should always be set.
private long
mNextId
The counter for unique IDs.
private int
mNextRequestCode
The counter for unique request codes.
private android.content.SharedPreferences
mSharedPreferences
Cached shared preferences.
private SharedPreferences.Editor
mEditor
If in no-commit mode, the shared editor to give out (which will be committed when exiting no-commit mode).
private boolean
mNoCommit
Blocks commits from happening on the shared editor. This is used when inflating the hierarchy. Do not set this directly, use {@link #setNoCommit(boolean)}
private String
mSharedPreferencesName
The SharedPreferences name that will be used for all {@link Preference}s managed by this instance.
private int
mSharedPreferencesMode
The SharedPreferences mode that will be used for all {@link Preference}s managed by this instance.
private PreferenceScreen
mPreferenceScreen
The {@link PreferenceScreen} at the root of the preference hierarchy.
private List
mActivityResultListeners
List of activity result listeners.
private List
mActivityStopListeners
List of activity stop listeners.
private List
mActivityDestroyListeners
List of activity destroy listeners.
private List
mPreferencesScreens
List of dialogs that should be dismissed when we receive onNewIntent in our PreferenceActivity.
private OnPreferenceTreeClickListener
mOnPreferenceTreeClickListener
Constructors Summary
PreferenceManager(android.app.Activity activity, int firstRequestCode)

    
        
        mActivity = activity;
        mNextRequestCode = firstRequestCode;
        
        init(activity);
    
private PreferenceManager(android.content.Context context)
This constructor should ONLY be used when getting default values from an XML preference hierarchy.

The {@link PreferenceManager#PreferenceManager(Activity)} should be used ANY time a preference will be displayed, since some preference types need an Activity for managed queries.

        init(context);
    
Methods Summary
voidaddPreferencesScreen(android.content.DialogInterface screen)

        synchronized (this) {
            
            if (mPreferencesScreens == null) {
                mPreferencesScreens = new ArrayList<DialogInterface>();
            }
            
            mPreferencesScreens.add(screen);
        }
    
public PreferenceScreencreatePreferenceScreen(android.content.Context context)

        final PreferenceScreen preferenceScreen = new PreferenceScreen(context, null);
        preferenceScreen.onAttachedToHierarchy(this);
        return preferenceScreen;
    
private voiddismissAllScreens()

        // Remove any of the previously shown preferences screens
        ArrayList<DialogInterface> screensToDismiss;

        synchronized (this) {
            
            if (mPreferencesScreens == null) {
                return;
            }
            
            screensToDismiss = new ArrayList<DialogInterface>(mPreferencesScreens);
            mPreferencesScreens.clear();
        }
        
        for (int i = screensToDismiss.size() - 1; i >= 0; i--) {
            screensToDismiss.get(i).dismiss();
        }
    
voiddispatchActivityDestroy()
Called by the {@link PreferenceManager} to dispatch the activity destroy event.

        List<OnActivityDestroyListener> list = null;
        
        synchronized (this) {
            if (mActivityDestroyListeners != null) {
                list = new ArrayList<OnActivityDestroyListener>(mActivityDestroyListeners);
            }
        }

        if (list != null) {
            final int N = list.size();
            for (int i = 0; i < N; i++) {
                list.get(i).onActivityDestroy();
            }
        }

        // Dismiss any PreferenceScreens still showing
        dismissAllScreens();
    
voiddispatchActivityResult(int requestCode, int resultCode, android.content.Intent data)
Called by the {@link PreferenceManager} to dispatch a subactivity result.

        List<OnActivityResultListener> list;
        
        synchronized (this) {
            if (mActivityResultListeners == null) return;
            list = new ArrayList<OnActivityResultListener>(mActivityResultListeners);
        }

        final int N = list.size();
        for (int i = 0; i < N; i++) {
            if (list.get(i).onActivityResult(requestCode, resultCode, data)) {
                break;
            }
        }
    
voiddispatchActivityStop()
Called by the {@link PreferenceManager} to dispatch the activity stop event.

        List<OnActivityStopListener> list;
        
        synchronized (this) {
            if (mActivityStopListeners == null) return;
            list = new ArrayList<OnActivityStopListener>(mActivityStopListeners);
        }

        final int N = list.size();
        for (int i = 0; i < N; i++) {
            list.get(i).onActivityStop();
        }
    
voiddispatchNewIntent(android.content.Intent intent)
Called by {@link PreferenceActivity} to dispatch the new Intent event.

param
intent The new Intent.

        dismissAllScreens();
    
public PreferencefindPreference(java.lang.CharSequence key)
Finds a {@link Preference} based on its key.

param
key The key of the preference to retrieve.
return
The {@link Preference} with the key, or null.
see
PreferenceGroup#findPreference(CharSequence)

        if (mPreferenceScreen == null) {
            return null;
        }
        
        return mPreferenceScreen.findPreference(key);
    
android.app.ActivitygetActivity()
Returns the activity that shows the preferences. This is useful for doing managed queries, but in most cases the use of {@link #getContext()} is preferred.

This will return null if this class was instantiated with a Context instead of Activity. For example, when setting the default values.

return
The activity that shows the preferences.
see
#mContext

        return mActivity;
    
android.content.ContextgetContext()
Returns the context. This is preferred over {@link #getActivity()} when possible.

return
The context.

        return mContext;
    
public static android.content.SharedPreferencesgetDefaultSharedPreferences(android.content.Context context)
Gets a SharedPreferences instance that points to the default file that is used by the preference framework in the given context.

param
context The context of the preferences whose values are wanted.
return
A SharedPreferences instance that can be used to retrieve and listen to values of the preferences.

        return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
                getDefaultSharedPreferencesMode());
    
private static intgetDefaultSharedPreferencesMode()

        return Context.MODE_PRIVATE;
    
private static java.lang.StringgetDefaultSharedPreferencesName(android.content.Context context)

        return context.getPackageName() + "_preferences";
    
SharedPreferences.EditorgetEditor()
Returns an editor to use when modifying the shared preferences.

Do NOT commit unless {@link #shouldCommit()} returns true.

return
An editor to use to write to shared preferences.
see
#shouldCommit()

        
        if (mNoCommit) {
            if (mEditor == null) {
                mEditor = getSharedPreferences().edit();
            }
            
            return mEditor;
        } else {
            return getSharedPreferences().edit();
        }
    
longgetNextId()
Called by a preference to get a unique ID in its hierarchy.

return
A unique ID.

        synchronized (this) {
            return mNextId++;
        }
    
intgetNextRequestCode()
Returns a request code that is unique for the activity. Each subsequent call to this method should return another unique request code.

return
A unique request code that will never be used by anyone other than the caller of this method.

        synchronized (this) {
            return mNextRequestCode++;
        }
    
android.preference.PreferenceManager$OnPreferenceTreeClickListenergetOnPreferenceTreeClickListener()

        return mOnPreferenceTreeClickListener;
    
PreferenceScreengetPreferenceScreen()
Returns the root of the preference hierarchy managed by this class.

return
The {@link PreferenceScreen} object that is at the root of the hierarchy.

        return mPreferenceScreen;
    
public android.content.SharedPreferencesgetSharedPreferences()
Gets a SharedPreferences instance that preferences managed by this will use.

return
A SharedPreferences instance pointing to the file that contains the values of preferences that are managed by this.

        if (mSharedPreferences == null) {
            mSharedPreferences = mContext.getSharedPreferences(mSharedPreferencesName,
                    mSharedPreferencesMode);
        }
        
        return mSharedPreferences;
    
public intgetSharedPreferencesMode()
Returns the current mode of the SharedPreferences file that preferences managed by this will use.

return
The mode that can be passed to {@link Context#getSharedPreferences(String, int)}.
see
Context#getSharedPreferences(String, int)

        return mSharedPreferencesMode;
    
public java.lang.StringgetSharedPreferencesName()
Returns the current name of the SharedPreferences file that preferences managed by this will use.

return
The name that can be passed to {@link Context#getSharedPreferences(String, int)}.
see
Context#getSharedPreferences(String, int)

        return mSharedPreferencesName;
    
PreferenceScreeninflateFromIntent(android.content.Intent queryIntent, PreferenceScreen rootPreferences)
Inflates a preference hierarchy from the preference hierarchies of {@link Activity Activities} that match the given {@link Intent}. An {@link Activity} defines its preference hierarchy with meta-data using the {@link #METADATA_KEY_PREFERENCES} key.

If a preference hierarchy is given, the new preference hierarchies will be merged in.

param
queryIntent The intent to match activities.
param
rootPreferences Optional existing hierarchy to merge the new hierarchies into.
return
The root hierarchy (if one was not provided, the new hierarchy's root).

        final List<ResolveInfo> activities = queryIntentActivities(queryIntent);
        final HashSet<String> inflatedRes = new HashSet<String>();

        for (int i = activities.size() - 1; i >= 0; i--) {
            final ActivityInfo activityInfo = activities.get(i).activityInfo;
            final Bundle metaData = activityInfo.metaData;

            if ((metaData == null) || !metaData.containsKey(METADATA_KEY_PREFERENCES)) {
                continue;
            }

            // Need to concat the package with res ID since the same res ID
            // can be re-used across contexts
            final String uniqueResId = activityInfo.packageName + ":"
                    + activityInfo.metaData.getInt(METADATA_KEY_PREFERENCES);
            
            if (!inflatedRes.contains(uniqueResId)) {
                inflatedRes.add(uniqueResId);

                final Context context;
                try {
                    context = mContext.createPackageContext(activityInfo.packageName, 0);
                } catch (NameNotFoundException e) {
                    Log.w(TAG, "Could not create context for " + activityInfo.packageName + ": "
                        + Log.getStackTraceString(e));
                    continue;
                }
                
                final PreferenceInflater inflater = new PreferenceInflater(context, this);
                final XmlResourceParser parser = activityInfo.loadXmlMetaData(context
                        .getPackageManager(), METADATA_KEY_PREFERENCES);
                rootPreferences = (PreferenceScreen) inflater
                        .inflate(parser, rootPreferences, true);
                parser.close();
            }
        }

        rootPreferences.onAttachedToHierarchy(this);
        
        return rootPreferences;
    
PreferenceScreeninflateFromResource(android.content.Context context, int resId, PreferenceScreen rootPreferences)
Inflates a preference hierarchy from XML. If a preference hierarchy is given, the new preference hierarchies will be merged in.

param
context The context of the resource.
param
resId The resource ID of the XML to inflate.
param
rootPreferences Optional existing hierarchy to merge the new hierarchies into.
return
The root hierarchy (if one was not provided, the new hierarchy's root).

        // Block commits
        setNoCommit(true);

        final PreferenceInflater inflater = new PreferenceInflater(context, this);
        rootPreferences = (PreferenceScreen) inflater.inflate(resId, rootPreferences, true);
        rootPreferences.onAttachedToHierarchy(this);

        // Unblock commits
        setNoCommit(false);

        return rootPreferences;
    
private voidinit(android.content.Context context)

        mContext = context;
        
        setSharedPreferencesName(getDefaultSharedPreferencesName(context));
    
private java.util.ListqueryIntentActivities(android.content.Intent queryIntent)
Returns a list of {@link Activity} (indirectly) that match a given {@link Intent}.

param
queryIntent The Intent to match.
return
The list of {@link ResolveInfo} that point to the matched activities.

        return mContext.getPackageManager().queryIntentActivities(queryIntent,
                PackageManager.GET_META_DATA);
    
voidregisterOnActivityDestroyListener(android.preference.PreferenceManager$OnActivityDestroyListener listener)
Registers a listener.

see
OnActivityDestroyListener

        synchronized (this) {
            if (mActivityDestroyListeners == null) {
                mActivityDestroyListeners = new ArrayList<OnActivityDestroyListener>();
            }

            if (!mActivityDestroyListeners.contains(listener)) {
                mActivityDestroyListeners.add(listener);
            }
        }
    
voidregisterOnActivityResultListener(android.preference.PreferenceManager$OnActivityResultListener listener)
Registers a listener.

see
OnActivityResultListener

        synchronized (this) {
            if (mActivityResultListeners == null) {
                mActivityResultListeners = new ArrayList<OnActivityResultListener>();
            }
            
            if (!mActivityResultListeners.contains(listener)) {
                mActivityResultListeners.add(listener);
            }
        }
    
voidregisterOnActivityStopListener(android.preference.PreferenceManager$OnActivityStopListener listener)
Registers a listener.

see
OnActivityStopListener

        synchronized (this) {
            if (mActivityStopListeners == null) {
                mActivityStopListeners = new ArrayList<OnActivityStopListener>();
            }
            
            if (!mActivityStopListeners.contains(listener)) {
                mActivityStopListeners.add(listener);
            }
        }
    
voidremovePreferencesScreen(android.content.DialogInterface screen)

        synchronized (this) {
            
            if (mPreferencesScreens == null) {
                return;
            }
            
            mPreferencesScreens.remove(screen);
        }
    
public static voidsetDefaultValues(android.content.Context context, int resId, boolean readAgain)
Sets the default values from a preference hierarchy in XML. This should be called by the application's main activity.

If {@code readAgain} is false, this will only set the default values if this method has never been called in the past (or the {@link #KEY_HAS_SET_DEFAULT_VALUES} in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set {@code readAgain} to true.

param
context The context of the shared preferences.
param
resId The resource ID of the preference hierarchy XML file.
param
readAgain Whether to re-read the default values.

Note: this will NOT reset preferences back to their default values. For that functionality, use {@link PreferenceManager#getDefaultSharedPreferences(Context)} and clear it followed by a call to this method with this parameter set to true.

        
        // Use the default shared preferences name and mode
        setDefaultValues(context, getDefaultSharedPreferencesName(context),
                getDefaultSharedPreferencesMode(), resId, readAgain);
    
public static voidsetDefaultValues(android.content.Context context, java.lang.String sharedPreferencesName, int sharedPreferencesMode, int resId, boolean readAgain)
Similar to {@link #setDefaultValues(Context, int, boolean)} but allows the client to provide the filename and mode of the shared preferences file.

see
#setDefaultValues(Context, int, boolean)
see
#setSharedPreferencesName(String)
see
#setSharedPreferencesMode(int)

        final SharedPreferences defaultValueSp = context.getSharedPreferences(
                KEY_HAS_SET_DEFAULT_VALUES, Context.MODE_PRIVATE);
        
        if (readAgain || !defaultValueSp.getBoolean(KEY_HAS_SET_DEFAULT_VALUES, false)) {
            final PreferenceManager pm = new PreferenceManager(context);
            pm.setSharedPreferencesName(sharedPreferencesName);
            pm.setSharedPreferencesMode(sharedPreferencesMode);
            pm.inflateFromResource(context, resId, null);

            defaultValueSp.edit().putBoolean(KEY_HAS_SET_DEFAULT_VALUES, true).commit();
        }
    
private voidsetNoCommit(boolean noCommit)

        if (!noCommit && mEditor != null) {
            mEditor.commit();
        }
        
        mNoCommit = noCommit;
    
voidsetOnPreferenceTreeClickListener(android.preference.PreferenceManager$OnPreferenceTreeClickListener listener)
Sets the callback to be invoked when a {@link Preference} in the hierarchy rooted at this {@link PreferenceManager} is clicked.

param
listener The callback to be invoked.

        mOnPreferenceTreeClickListener = listener;
    
booleansetPreferences(PreferenceScreen preferenceScreen)
Sets the root of the preference hierarchy.

param
preferenceScreen The root {@link PreferenceScreen} of the preference hierarchy.
return
Whether the {@link PreferenceScreen} given is different than the previous.

        if (preferenceScreen != mPreferenceScreen) {
            mPreferenceScreen = preferenceScreen;
            return true;
        }
        
        return false;
    
public voidsetSharedPreferencesMode(int sharedPreferencesMode)
Sets the mode of the SharedPreferences file that preferences managed by this will use.

param
sharedPreferencesMode The mode of the SharedPreferences file.
see
Context#getSharedPreferences(String, int)

        mSharedPreferencesMode = sharedPreferencesMode;
        mSharedPreferences = null;
    
public voidsetSharedPreferencesName(java.lang.String sharedPreferencesName)
Sets the name of the SharedPreferences file that preferences managed by this will use.

param
sharedPreferencesName The name of the SharedPreferences file.
see
Context#getSharedPreferences(String, int)

        mSharedPreferencesName = sharedPreferencesName;
        mSharedPreferences = null;
    
booleanshouldCommit()
Whether it is the client's responsibility to commit on the {@link #getEditor()}. This will return false in cases where the writes should be batched, for example when inflating preferences from XML.

return
Whether the client should commit.

        return !mNoCommit;
    
voidunregisterOnActivityDestroyListener(android.preference.PreferenceManager$OnActivityDestroyListener listener)
Unregisters a listener.

see
OnActivityDestroyListener

        synchronized (this) {
            if (mActivityDestroyListeners != null) {
                mActivityDestroyListeners.remove(listener);
            }
        }
    
voidunregisterOnActivityResultListener(android.preference.PreferenceManager$OnActivityResultListener listener)
Unregisters a listener.

see
OnActivityResultListener

        synchronized (this) {
            if (mActivityResultListeners != null) {
                mActivityResultListeners.remove(listener);
            }
        }
    
voidunregisterOnActivityStopListener(android.preference.PreferenceManager$OnActivityStopListener listener)
Unregisters a listener.

see
OnActivityStopListener

        synchronized (this) {
            if (mActivityStopListeners != null) {
                mActivityStopListeners.remove(listener);
            }
        }