This guide is intended for developers of Chrome for Android who need to read and/or write small amounts of data from Java to a persistent key-value store.
SharedPreferencesManager
is a lightweight wrapper around Android SharedPreferences to handle additional key management logic in Chrome. It supports reading and writing simple key-value pairs to a file that is saved across app sessions.
PrefService
is a JNI bridge providing access to a native Chrome PrefService instance associated. This interface can be used to read and write prefs once they're registered through the PrefRegistry
and exposed to Java by way of a java_cpp_strings
build target such as this one.
Should I use SharedPreferences or PrefService?
Ask yourself the following questions about the preference to be stored:
If the answer to one or more of the above questions is Yes, then the preference should be stored in PrefService. If the answer to all of the above questions is No, then SharedPreferences should be preferred.
What if the PrefService type I need to access is not supported by PrefService (i.e. double, Time, etc.)?
If a base value type is supported by PrefService, then PrefService should be extended to support it once it's needed.
How do I access a PrefService pref associated with local state rather than browser profile?
Most Chrome for Android preferences should be associated with a specific profile. If your preference should instead be associated with local state (for example, if it is related to the First Run Experience), then you should not use PrefService and should instead create your own feature-specific JNI bridge to access the correct PrefService instance (see first_run_utils.cc
).
Can I move a pref from SharedPreferences to PrefService?
In general, SharedPreferences are not exposed to C++. There is limited support in shared_preferences_migrator_android.h
for reading, writing, and clearing values from SharedPreferences.
Should I use the default SharedPreferences or create my own?
You should prefer to use the default one through SharedPreferencesManager
unless you are going to store large amounts of data.
Rationale: