android实例教程
In this tutorial we’ll use Shared Preferences in our android application to store data in the form of key-value pair.
n
在本教程中,我们将在Android应用程序中使用“ 共享首选项 ”以键值对的形式存储数据。
ñ
Android共享首选项概述 ()
Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.
共享首选项允许活动和应用程序以键-值对的形式保留首选项,类似于键映射对,即使用户关闭应用程序,该映射也将保留。
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory()
.
Android将“共享首选项”设置作为XML文件存储在DATA / data / {application package}目录下的shared_prefs文件夹中。 可以通过调用Environment.getDataDirectory()
获得DATA文件夹。
SharedPreferences is application specific, i.e. the data is lost on performing one of the following options:
SharedPreferences是特定于应用程序的,即在执行以下选项之一时数据会丢失:
- on uninstalling the application 关于卸载应用程序
- on clearing the application data (through Settings) 清除应用程序数据时(通过“设置”)
As the name suggests, the primary purpose is to store user-specified configuration details, such as user specific settings, keeping the user logged into the application.
顾名思义,其主要目的是存储用户指定的配置详细信息,例如用户特定的设置,以保持用户登录到应用程序中。
To get access to the preferences, we have three APIs to choose from:
要访问首选项,我们提供了三种API供您选择:
- getPreferences() : used from within your Activity, to access activity-specific preferences getPreferences() :从您的“活动”内部使用,以访问特定于活动的首选项
- getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences getSharedPreferences() :从您的Activity(或其他应用程序上下文)内部使用,用于访问应用程序级首选项
- getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framewor