1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17 package android.content; 18 19 import android.annotation.Nullable; 20 21 import java.util.Map; 22 import java.util.Set; 23 24 /** 25 * Interface for accessing and modifying preference data returned by {@link 26 * Context#getSharedPreferences}. For any particular set of preferences, 27 * there is a single instance of this class that all clients share. 28 * Modifications to the preferences must go through an {@link Editor} object 29 * to ensure the preference values remain in a consistent state and control 30 * when they are committed to storage. Objects that are returned from the 31 * various <code>get</code> methods must be treated as immutable by the application. 32 * 33 * <p>SharedPreferences is best suited to storing data about how the user prefers 34 * to experience the app, for example, whether the user prefers a particular UI theme 35 * or whether they prefer viewing particular content in a list vs. a grid. To this end, 36 * SharedPreferences reflects changes {@link Editor#commit() committed} or 37 * {@link Editor#apply() applied} by {@link Editor}s <em>immediately</em>, potentially 38 * before those changes are durably persisted. 39 * Under some circumstances such as app crashes or termination these changes may be lost, 40 * even if an {@link OnSharedPreferenceChangeListener} reported the change was successful. 41 * SharedPreferences is not recommended for storing data that is sensitive to this 42 * kind of rollback to a prior state such as user security or privacy settings. 43 * For other high-level data persistence options, see 44 * <a href="https://d.android.com/room">Room</a> or 45 * <a href="https://d.android.com/datastore">DataStore</a>. 46 * 47 * <p><em>Note:</em> Common implementations guarantee that outstanding edits to preference 48 * files are persisted to disk when host Activities become stopped. In some situations 49 * (e.g. performing many {@link Editor#commit()} or {@link Editor#apply()} 50 * operations just prior to navigating away from the host Activity) this can lead 51 * to blocking the main thread during lifecycle transition events and associated 52 * ANR errors. For more details see the documentation for {@link Editor#commit()} and 53 * {@link Editor#apply()}. 54 * 55 * <p><em>Note: This class does not support use across multiple processes.</em> 56 * 57 * <div class="special reference"> 58 * <h3>Developer Guides</h3> 59 * <p>For more information about using SharedPreferences, read the 60 * <a href="{@docRoot}guide/topics/data/data-storage.html#pref">Data Storage</a> 61 * developer guide.</p></div> 62 * 63 * @see Context#getSharedPreferences 64 */ 65 public interface SharedPreferences { 66 /** 67 * Interface definition for a callback to be invoked when a shared 68 * preference is changed. 69 */ 70 public interface OnSharedPreferenceChangeListener { 71 /** 72 * Called when a shared preference is changed, added, or removed. This 73 * may be called even if a preference is set to its existing value. 74 * 75 * <p>This callback will be run on your main thread. 76 * 77 * <p><em>Note: This callback will not be triggered when preferences are cleared 78 * via {@link Editor#clear()}, unless targeting {@link android.os.Build.VERSION_CODES#R} 79 * on devices running OS versions {@link android.os.Build.VERSION_CODES#R Android R} 80 * or later.</em> 81 * 82 * @param sharedPreferences The {@link SharedPreferences} that received the change. 83 * @param key The key of the preference that was changed, added, or removed. Apps targeting 84 * {@link android.os.Build.VERSION_CODES#R} on devices running OS versions 85 * {@link android.os.Build.VERSION_CODES#R Android R} or later, will receive 86 * a {@code null} value when preferences are cleared. 87 */ onSharedPreferenceChanged(SharedPreferences sharedPreferences, @Nullable String key)88 void onSharedPreferenceChanged(SharedPreferences sharedPreferences, @Nullable String key); 89 } 90 91 /** 92 * Interface used for modifying values in a {@link SharedPreferences} 93 * object. All changes you make in an editor are batched, and not copied 94 * back to the original {@link SharedPreferences} until you call {@link #commit} 95 * or {@link #apply} 96 */ 97 public interface Editor { 98 /** 99 * Set a String value in the preferences editor, to be written back once 100 * {@link #commit} or {@link #apply} are called. 101 * 102 * @param key The name of the preference to modify. 103 * @param value The new value for the preference. Passing {@code null} 104 * for this argument is equivalent to calling {@link #remove(String)} with 105 * this key. 106 * 107 * @return Returns a reference to the same Editor object, so you can 108 * chain put calls together. 109 */ putString(String key, @Nullable String value)110 Editor putString(String key, @Nullable String value); 111 112 /** 113 * Set a set of String values in the preferences editor, to be written 114 * back once {@link #commit} or {@link #apply} is called. 115 * 116 * @param key The name of the preference to modify. 117 * @param values The set of new values for the preference. Passing {@code null} 118 * for this argument is equivalent to calling {@link #remove(String)} with 119 * this key. 120 * @return Returns a reference to the same Editor object, so you can 121 * chain put calls together. 122 */ putStringSet(String key, @Nullable Set<String> values)123 Editor putStringSet(String key, @Nullable Set<String> values); 124 125 /** 126 * Set an int value in the preferences editor, to be written back once 127 * {@link #commit} or {@link #apply} are called. 128 * 129 * @param key The name of the preference to modify. 130 * @param value The new value for the preference. 131 * 132 * @return Returns a reference to the same Editor object, so you can 133 * chain put calls together. 134 */ putInt(String key, int value)135 Editor putInt(String key, int value); 136 137 /** 138 * Set a long value in the preferences editor, to be written back once 139 * {@link #commit} or {@link #apply} are called. 140 * 141 * @param key The name of the preference to modify. 142 * @param value The new value for the preference. 143 * 144 * @return Returns a reference to the same Editor object, so you can 145 * chain put calls together. 146 */ putLong(String key, long value)147 Editor putLong(String key, long value); 148 149 /** 150 * Set a float value in the preferences editor, to be written back once 151 * {@link #commit} or {@link #apply} are called. 152 * 153 * @param key The name of the preference to modify. 154 * @param value The new value for the preference. 155 * 156 * @return Returns a reference to the same Editor object, so you can 157 * chain put calls together. 158 */ putFloat(String key, float value)159 Editor putFloat(String key, float value); 160 161 /** 162 * Set a boolean value in the preferences editor, to be written back 163 * once {@link #commit} or {@link #apply} are called. 164 * 165 * @param key The name of the preference to modify. 166 * @param value The new value for the preference. 167 * 168 * @return Returns a reference to the same Editor object, so you can 169 * chain put calls together. 170 */ putBoolean(String key, boolean value)171 Editor putBoolean(String key, boolean value); 172 173 /** 174 * Mark in the editor that a preference value should be removed, which 175 * will be done in the actual preferences once {@link #commit} is 176 * called. 177 * 178 * <p>Note that when committing back to the preferences, all removals 179 * are done first, regardless of whether you called remove before 180 * or after put methods on this editor. 181 * 182 * @param key The name of the preference to remove. 183 * 184 * @return Returns a reference to the same Editor object, so you can 185 * chain put calls together. 186 */ remove(String key)187 Editor remove(String key); 188 189 /** 190 * Mark in the editor to remove <em>all</em> values from the 191 * preferences. Once commit is called, the only remaining preferences 192 * will be any that you have defined in this editor. 193 * 194 * <p>Note that when committing back to the preferences, the clear 195 * is done first, regardless of whether you called clear before 196 * or after put methods on this editor. 197 * 198 * @return Returns a reference to the same Editor object, so you can 199 * chain put calls together. 200 */ clear()201 Editor clear(); 202 203 /** 204 * Commit your preferences changes back from this Editor to the 205 * {@link SharedPreferences} object it is editing. This atomically 206 * performs the requested modifications, replacing whatever is currently 207 * in the SharedPreferences. 208 * 209 * <p>Note that when two editors are modifying preferences at the same 210 * time, the last one to call commit wins. 211 * 212 * <p>If you don't care about the return value and you're 213 * using this from your application's main thread, consider 214 * using {@link #apply} instead. 215 * 216 * @return Returns true if the new values were successfully written 217 * to persistent storage. 218 */ commit()219 boolean commit(); 220 221 /** 222 * Commit your preferences changes back from this Editor to the 223 * {@link SharedPreferences} object it is editing. This atomically 224 * performs the requested modifications, replacing whatever is currently 225 * in the SharedPreferences. 226 * 227 * <p>Note that when two editors are modifying preferences at the same 228 * time, the last one to call apply wins. 229 * 230 * <p>Unlike {@link #commit}, which writes its preferences out 231 * to persistent storage synchronously, {@link #apply} 232 * commits its changes to the in-memory 233 * {@link SharedPreferences} immediately but starts an 234 * asynchronous commit to disk and you won't be notified of 235 * any failures. If another editor on this 236 * {@link SharedPreferences} does a regular {@link #commit} 237 * while a {@link #apply} is still outstanding, the 238 * {@link #commit} will block until all async commits are 239 * completed as well as the commit itself. 240 * 241 * <p>As {@link SharedPreferences} instances are singletons within 242 * a process, it's safe to replace any instance of {@link #commit} with 243 * {@link #apply} if you were already ignoring the return value. 244 * 245 * <p>You don't need to worry about Android component 246 * lifecycles and their interaction with <code>apply()</code> 247 * writing to disk. The framework makes sure in-flight disk 248 * writes from <code>apply()</code> complete before switching 249 * states. 250 * 251 * <p class='note'>The SharedPreferences.Editor interface 252 * isn't expected to be implemented directly. However, if you 253 * previously did implement it and are now getting errors 254 * about missing <code>apply()</code>, you can simply call 255 * {@link #commit} from <code>apply()</code>. 256 */ apply()257 void apply(); 258 } 259 260 /** 261 * Retrieve all values from the preferences. 262 * 263 * <p>Note that you <em>must not</em> modify the collection returned 264 * by this method, or alter any of its contents. The consistency of your 265 * stored data is not guaranteed if you do. 266 * 267 * @return Returns a map containing a list of pairs key/value representing 268 * the preferences. 269 * 270 * @throws NullPointerException 271 */ getAll()272 Map<String, ?> getAll(); 273 274 /** 275 * Retrieve a String value from the preferences. 276 * 277 * @param key The name of the preference to retrieve. 278 * @param defValue Value to return if this preference does not exist. 279 * 280 * @return Returns the preference value if it exists, or defValue. Throws 281 * ClassCastException if there is a preference with this name that is not 282 * a String. 283 * 284 * @throws ClassCastException 285 */ 286 @Nullable getString(String key, @Nullable String defValue)287 String getString(String key, @Nullable String defValue); 288 289 /** 290 * Retrieve a set of String values from the preferences. 291 * 292 * <p>Note that you <em>must not</em> modify the set instance returned 293 * by this call. The consistency of the stored data is not guaranteed 294 * if you do, nor is your ability to modify the instance at all. 295 * 296 * @param key The name of the preference to retrieve. 297 * @param defValues Values to return if this preference does not exist. 298 * 299 * @return Returns the preference values if they exist, or defValues. 300 * Throws ClassCastException if there is a preference with this name 301 * that is not a Set. 302 * 303 * @throws ClassCastException 304 */ 305 @Nullable getStringSet(String key, @Nullable Set<String> defValues)306 Set<String> getStringSet(String key, @Nullable Set<String> defValues); 307 308 /** 309 * Retrieve an int value from the preferences. 310 * 311 * @param key The name of the preference to retrieve. 312 * @param defValue Value to return if this preference does not exist. 313 * 314 * @return Returns the preference value if it exists, or defValue. Throws 315 * ClassCastException if there is a preference with this name that is not 316 * an int. 317 * 318 * @throws ClassCastException 319 */ getInt(String key, int defValue)320 int getInt(String key, int defValue); 321 322 /** 323 * Retrieve a long value from the preferences. 324 * 325 * @param key The name of the preference to retrieve. 326 * @param defValue Value to return if this preference does not exist. 327 * 328 * @return Returns the preference value if it exists, or defValue. Throws 329 * ClassCastException if there is a preference with this name that is not 330 * a long. 331 * 332 * @throws ClassCastException 333 */ getLong(String key, long defValue)334 long getLong(String key, long defValue); 335 336 /** 337 * Retrieve a float value from the preferences. 338 * 339 * @param key The name of the preference to retrieve. 340 * @param defValue Value to return if this preference does not exist. 341 * 342 * @return Returns the preference value if it exists, or defValue. Throws 343 * ClassCastException if there is a preference with this name that is not 344 * a float. 345 * 346 * @throws ClassCastException 347 */ getFloat(String key, float defValue)348 float getFloat(String key, float defValue); 349 350 /** 351 * Retrieve a boolean value from the preferences. 352 * 353 * @param key The name of the preference to retrieve. 354 * @param defValue Value to return if this preference does not exist. 355 * 356 * @return Returns the preference value if it exists, or defValue. Throws 357 * ClassCastException if there is a preference with this name that is not 358 * a boolean. 359 * 360 * @throws ClassCastException 361 */ getBoolean(String key, boolean defValue)362 boolean getBoolean(String key, boolean defValue); 363 364 /** 365 * Checks whether the preferences contains a preference. 366 * 367 * @param key The name of the preference to check. 368 * @return Returns true if the preference exists in the preferences, 369 * otherwise false. 370 */ contains(String key)371 boolean contains(String key); 372 373 /** 374 * Create a new Editor for these preferences, through which you can make 375 * modifications to the data in the preferences and atomically commit those 376 * changes back to the SharedPreferences object. 377 * 378 * <p>Note that you <em>must</em> call {@link Editor#commit} to have any 379 * changes you perform in the Editor actually show up in the 380 * SharedPreferences. 381 * 382 * @return Returns a new instance of the {@link Editor} interface, allowing 383 * you to modify the values in this SharedPreferences object. 384 */ edit()385 Editor edit(); 386 387 /** 388 * Registers a callback to be invoked when a change happens to a preference. 389 * 390 * <p class="caution"><strong>Caution:</strong> The preference manager does 391 * not currently store a strong reference to the listener. You must store a 392 * strong reference to the listener, or it will be susceptible to garbage 393 * collection. We recommend you keep a reference to the listener in the 394 * instance data of an object that will exist as long as you need the 395 * listener.</p> 396 * 397 * @param listener The callback that will run. 398 * @see #unregisterOnSharedPreferenceChangeListener 399 */ registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener)400 void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener); 401 402 /** 403 * Unregisters a previous callback. 404 * 405 * @param listener The callback that should be unregistered. 406 * @see #registerOnSharedPreferenceChangeListener 407 */ unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener)408 void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener); 409 } 410