标签:
Data Storage 数据保存
Store application data in databases, files, or preferences, in internal or removeable storage. You can also add a data backup service to let users store and recover application and
system data.
可以在数据库,文件,内部储存,可移动储存中,储存应用程序的数据。你也可以增加一个数据备份服务来让用户保存和恢复应用程序和系统数据。
Syncing to the Cloud 同步到云
This class covers different strategies for cloud enabled applications. It covers syncing data with the cloud using your own back-end web application, and backing up data using the
cloud so that users can restore their data when installing your application on a new device.
这个分类中包含了云程序的不同策略。包括使用自己的后端web程序将数据同步到云,并使用云备份数据,让用户在新设备上安装程序时恢复数据。
Storage Options
Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to
your application or accessible to other applications (and the user) and how much space your data requires.
Android为你提供了几种持久化保存应用数据的选项。 你依赖特殊的需求可以选择解决方案。比如数据是否对于你的应用程序是私有的或可以被其他应用程序访问,或你的数据需要多少空间。
Your data storage options are the following: 下面是你储存数据的选项:
Shared Preferences
Store private primitive data in key-value pairs. 以键值对保存私有数据
Internal Storage
Store private data on the device memory. 在设备存储器上保存私有数据
External Storage
Store public data on the shared external storage. 在共享存储器上保存公共数据
SQLite Databases
Store structured data in a private database. 在私有数据中保存结构化数据
Network Connection
Store data on the web with your own network server. 通过网络在网络服务器上保存数据
Android provides a way for you to expose even your private data to other applications — with a content provider. A content provider is an optional component that exposes read/write
access to your application data, subject to whatever restrictions you want to impose. For more information about using content providers, see the Content Providers documentation.
Android为你提供了一种提供你的私有数据给其他应用程序的方式--使用内容提供者。内容提供者是一个可选的组件,为你的读写应用的数据,这个选择取决于你给定的限制。如果想知道更多关于内容提供者的信息,可以看下内容提供者的文档。
Using Shared Preferences
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save
any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
SharedPreferences类提供了一个通用的框架,允许你保存和读取持久化键值对的原始私有数据类型。
你可以使用SharedPreferences保存私有数据:boolean,floats,ints,longs,和string。这些数据持久的保存在用户的会话中(即使应用程序退出)
User Preferences用户属性
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you‘re interested in creating user preferences for your application,
seePreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
共享属性并不是严格意义上为了保存用户属性的,比如用户选择的铃声。如果你对为应用程序创建用户属性很感兴趣。可以看PreferenceActivity.这个类为你提供了一个Activity框架来保存用户属性,它可以自动持久化(使用SharedPreference)
To get a SharedPreferences object for your application, use one of two methods:
得到应用的SharedPreferences对象,使用两个方法:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
如果你需要通过名字来定义多个属性文件,你可以使用第一个参数来指定。
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don‘t supply a name.
如果一个Activity只需要一个属性文件。因为Activity只有一个属性文件,所以不需要提供名字
To write values: 写入值:
Call edit() to get a SharedPreferences.Editor. 调用edit()得到SharedPreferences.Editor
Add values with methods such as putBoolean() and putString(). 使用putBoolean()和putString()去添加值
Commit the new values with commit() 使用commit()去提交新值
To read values, use SharedPreferences methods such as getBoolean() and getString().
读取值,使用 SharedPreferences的getBoolean() 和 getString()
Here is an example that saves a preference for silent keypress mode in a calculator:
这里有一个例子是保存计算器的无声按键模式。
public class Calc extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
@Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
Using the Internal Storage 使用内部储存
You can save files directly on the device‘s internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them
(nor can the user). When the user uninstalls your application, these files are removed.
你可以直接在设备的内部存储上保存文件。默认,文件保存在内部储存器对你的应用是私有的,其他应用程序是不能访问的。当用户卸载你的应用的时候,这些文件会被删除。
To create and write a private file to the internal storage: 创建并写私有文件到内部储存器中:
Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.
Write to the file with write().
Close the stream with close().
For example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
私有模式创建文件(或替换相同名字的文件)并私有化。
To read a file from internal storage: 从内部储存中读取一个文件:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
调用openFileInput()并传递文件的名字去读。返回一个FileInputStream。
Read bytes from the file with read(). 通过read()从文件中读取字节
Then close the stream with close(). 通过close()关闭流。
Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw.<filename>resource
ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).
如果你想在编译的时候,保存一个静态文件在你的应用中。你可以把文件保存在res/raw目录下。你可以通过openRawResource()打开它,传递 R.raw.<filename> 资源ID。这个方法返回一个输入流,你可以读取这个文件。(但是你不能写这个文件)
Saving cache files 保存缓存文件
If you‘d like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should
save temporary cache files.
如果你想缓存一些数据,而不是持久化保存。当你的应用保存临时的缓存文件的时候,你可以使用getCacheDir()去打开保存在内部储存器目录上的文件。
When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you.
You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.
当你设备的内部储存器的空间比较少的时候,Android会删除那些缓存文件去回收空间。但是,你不能依赖系统给你清理这些文件。你必须持续关注缓存文件保持在一个合理控制的空间消耗,比如1M。当用户卸载你的应用的时候,这些文件被删除。
Other useful methods
getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
得到内部储存器的绝对路径
getDir()
Creates (or opens an existing) directory within your internal storage space.
在内部存储器上创建(或打开一个已经存在)目录
deleteFile()
Deletes a file saved on the internal storage.
在内部存储器上删除文件
fileList()
Returns an array of files currently saved by your application.
返回你的应用的当前保存的文件集合
Using the External Storage 使用外部存储器
Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable)
storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
所有兼容Android的设备都支持共享的外部存储,去可以保存文件。外部存储可以是一个可移动的储存设备(比如SD卡)或内部储存器。当通过USB传输文件给电脑的时候,保存在外部储存器的文件是可读的,并可以被用户修改。
Caution: External storage can become unavailable if the user mounts the external storage on a computer or removes the media, and there‘s no security enforced upon files you save to
the external storage. All applications can read and write files placed on the external storage and the user can remove them.
如果用户挂载外部设备在电脑上或移动媒介,外部储存变得不可用。这些保存保存在外部存储器上的文件没有强制的安全措施。所有的应用程序都可以读写保存在外部存储器上的文件,并可以删除它们。
Getting access to external storage
In order to read or write files on the external storage, your app must acquire theREAD_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. For example:
为了在外部存储器上读或写文件,你的应用需要系统权限。
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
If you need to both read and write files, then you need to request only the WRITE_EXTERNAL_STORAGEpermission, because it implicitly requires read access as well.
如果你需要读和写的权限,你只需要请求写权限,因为它隐含的也请求了读权限。
Note: Beginning with Android 4.4, these permissions are not required if you‘re reading or writing only files that are private to your app. For more information, see the section below
about saving files that are app-private.
在Android4.4开始,这些权限不再需要,如果只是读或写你应用的所有文件。如果你想了解更过信息,看下保存app的私有文件这部分。
Checking media availability
Before you do any work with the external storage, you should always call getExternalStorageState()to check whether the media is available. The media might be mounted to a computer,
missing, read-only, or in some other state. For example, here are a couple methods you can use to check the availability:
在外部存储器做任何事情之前,你必须调用getExternalStorageState()去检查介质是否可用。介质可能挂载在电脑上,可能丢失,可能只读,或其他一些状态。例如,这里有一对方法来检查介质是否可用:
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
The getExternalStorageState() method returns other states that you might want to check, such as whether the media is being shared (connected to a computer), is missing entirely, has
been removed badly, etc. You can use these to notify the user with more information when your application needs to access the media.
getExternalStorageState()返回你想要检测的其他状态,比如是否介质被共享(连接电脑),或全部丢失,会被移除。当你的应用需要访问介质的时候,你可以提示用户更多信息。
Saving files that can be shared with other apps
Hiding your files from the Media Scanner
在介质扫描器中隐藏你的文件
Include an empty file named.nomedia in your external files directory (note the dot prefix in the filename). This prevents media scanner from reading your media files and providing
them to other apps through the MediaStore content provider. However, if your files are truly private to your app, you shouldsave them in an app-private directory.
在外部储存器上保存一个以.nomedia为名字的空文件(以点作前缀的文件名),它阻止介质扫描器读取介质中的文件,并且通过媒体库内容提供者提供给其他应用程序。但是,如果这些文件对你的应用是私有的,你必须保存他们在应用私有目录。
Generally, new files that the user may acquire through your app should be saved to a "public" location on the device where other apps can access them and the user can easily copy them
from the device. When doing so, you should use to one of the shared public directories, such as Music/,Pictures/, and Ringtones/.
一般来说,用户通过应用程序获取新文件保存在设备的公共位置,其他应用可以访问这些文件,并且用户可以很容易的从设备上复制这些文件。当我们要这么做的时候,你必须使用一个公共共享目录,比如Music,Picture,Ringtones
To get a File representing the appropriate public directory, call getExternalStoragePublicDirectory(), passing it the type of directory you want, such as DIRECTORY_MUSIC,DIRECTORY_PICTURES,
DIRECTORY_RINGTONES, or others. By saving your files to the corresponding media-type directory, the system‘s media scanner can properly categorize your files in the system (for instance, ringtones appear in system settings as ringtones, not as music).
为了获得合适的公共目录,调用getExternalStoragePublicDirectory(),传递你想要的目录类型,比如音乐目录,图片目录,铃声目录等等。通过相应的目录类型保存文件,系统的介质扫描者可以在系统中分类你的文件(举个例子,铃声应该出现在系统设置中铃声目录中,而不是在音乐目录中)
For example, here‘s a method that creates a directory for a new photo album in the public pictures directory:
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user‘s public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
Saving files that are app-private
If you are handling files that are not intended for other apps to use (such as graphic textures or sound effects used by only your app), you should use a private storage directory
on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don‘t need a specific media directory, pass nullto receive the root directory of your app‘s
private directory.
如果你要处理并不想让其他应用使用的文件(比如只是你的应用中的图像或音效),你必须使用私有储存目录在外部储存器中,通过调用 getExternalFilesDir().这个方法也提供了一个类型参数去指定子目录(比如电影目录)。如果你不需要特殊的媒体目录,
传递null去设定根目录为你应用的私有目录。
Beginning with Android 4.4, reading or writing files in your app‘s private directories does not require the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permissions. So you can
declare the permission should be requested only on the lower versions of Android by adding the maxSdkVersionattribute:
在Android4.4开始,读和写你应用中的私有目录不需要读、写权限。所以你可以比较低的版本中声明权限。
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
...
</manifest>
Note: When the user uninstalls your application, this directory and all its contents are deleted. Also, the system media scanner does not read files in these directories, so they are
not accessible from the MediaStore content provider. As such, you should not use these directories for media that ultimately belongs to the user, such as photos captured or edited with your app, or music the user has purchased with your app—those files should
be saved in the public directories.
当你卸载你的应用,目录和它里面的内容可以被删除。当然,系统媒体扫描器不能读到这些目录,当然也不能用内提供内容提供者访问。比如,你不必使用这些目录作为只属于某个用户的媒体目录,比如使用你的应用捕获或修改的图片,或者通过你的app购买的音乐,这些目录你必须保存在公共目录中。
Sometimes, a device that has allocated a partition of the internal memory for use as the external storage may also offer an SD card slot. When such a device is running Android 4.3
and lower, thegetExternalFilesDir() method provides access to only the internal partition and your app cannot read or write to the SD card. Beginning with Android 4.4, however, you can access both locations by calling getExternalFilesDirs(), which returns
a File array with entries each location. The first entry in the array is considered the primary external storage and you should use that location unless it‘s full or unavailable. If you‘d like to access both possible locations while also supporting Android
4.3 and lower, use the support library‘s static method,ContextCompat.getExternalFilesDirs(). This also returns a File array, but always includes only one entry on Android 4.3 and lower.
有时候,一个设备会分配内部存储器的一部分为外部存储器提供sd卡的卡槽。当设备运行在Android4.3或更低的版本的时候,getExternalFilesDir()提供了只访问内部存储部分,而你的应用不能读写sd卡。在Android4.4,你可以通过 getExternalFilesDirs()访问两个位置,这个方法返回每一个位置的全部文件集合。数组的第一部分主要是私有的外部储存,除非外部储存满了或不可用。如果你想在Android4.3或更低的版本访问这两个位置,可以使用支持库的静态方法ContextCompat.getExternalFilesDirs(),这个方法返回一个文件集合,它只是在Android4.3及以下版本。
Caution Although the directories provided by getExternalFilesDir() and getExternalFilesDirs() are not accessible by the MediaStore content provider, other apps with the READ_EXTERNAL_STORAGEpermission
can access all files on the external storage, including these. If you need to completely restrict access for your files, you should instead write your files to the internal storage.
警告:尽管媒体库内容提供者不能通过getExternalFilesDir()和getExternalFilesDirs()访问目录,其他应用可以通过读取外部储存权限访问外部储存的所有文件,也包括这些。如果你需要完全严格的访问你的文件,你必须使用内部储存写你的文件。
Saving cache files
To open a File that represents the external storage directory where you should save cache files, call getExternalCacheDir(). If the user uninstalls your application, these files will
be automatically deleted.
用来保存缓存文件的外部储存目录,调用 getExternalCacheDir().如果你卸载你的应用,这些文件自动删除。
Similar to ContextCompat.getExternalFilesDirs(), mentioned above, you can also access a cache directory on a secondary external storage (if available) by callingContextCompat.getExternalCacheDirs().
与上面提到的ContextCompat.getExternalFilesDirs()类似,你也可以使用ContextCompat.getExternalCacheDirs().来访问第二外部储存的缓存文件。
Tip: To preserve file space and maintain your app‘s performance, it‘s important that you carefully manage your cache files and remove those that aren‘t needed anymore throughout your
app‘s lifecycle.
为了保护文件控件和维护应用的的性能。小心的管理你的缓存文件,在不需要的时候回收它们,是很重要的。
Using Databases
Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application.
Android提供过了对sqlite数据的库的全面支持。你在应用在类中通过名字创建的任何数据库都可以被访问,但是其他应用不行。
The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelperand override the onCreate() method, in which you can execute a SQLite command to create
tables in the database. For example:
这个访问创建了一个新的sqlite数据的子类,重写onCreate方法,在里面创建执行sql命令创建数据库表。
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DICTIONARY_TABLE_NAME = "dictionary";
private static final String DICTIONARY_TABLE_CREATE =
"CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DICTIONARY_TABLE_CREATE);
}
}
You can then get an instance of your SQLiteOpenHelper implementation using the constructor you‘ve defined. To write to and read from the database, call getWritableDatabase() andgetReadableDatabase(),
respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.
你可以你定义的构造函数获得SQLiteOpenHelper的实例。读写数据库,调用call getWritableDatabase() andgetReadableDatabase()。它们都返回SQLiteDatabase来表示数据库,并提供sqlite操作的方法。
Android does not impose any limitations beyond the standard SQLite concepts. We do recommend including an autoincrement value key field that can be used as a unique ID to quickly find
a record. This is not required for private data, but if you implement a content provider, you must include a unique ID using the BaseColumns._ID constant.
Android没有做任何的改变去超越标准的sqlite的思想。我们推荐创建一个自定增长的字段,作为唯一的标识ID,进行快速查询记录。
这对于私有数据不是唯一的,但是如果你实现了内容提供者,你必须包含一个唯一ID,使用BaseColumns._ID常量。
You can execute SQLite queries using the SQLiteDatabasequery() methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping,
and others. For complex queries, such as those that require column aliases, you should use SQLiteQueryBuilder, which provides several convienent methods for building queries.
你可以使用SQLiteDatabasequery()方法执行sqlite查询,这方法接收不同的查询参数,例如查询的表,条件,列,分组等。
对于复合查询,需要列的别名,你可以使用SQLiteQueryBuilder,它提供合适的方法去创建查询。
Every SQLite query will return a Cursor that points to all the rows found by the query. The Cursor is always the mechanism with which you can navigate results from a database query
and read rows and columns.
每一个sqlite查询都会返回一个指针。指针是导航数据库查询结果行和列的原理。
For sample apps that demonstrate how to use SQLite databases in Android, see the Note Pad and Searchable Dictionary applications.
这些例子证明了怎么在Android中使用sqlite数据库,看下Note Pad and Searchable Dictionary应用。
Database debugging
The Android SDK includes a sqlite3 database tool that allows you to browse table contents, run SQL commands, and perform other useful functions on SQLite databases. See Examining sqlite3
databases from a remote shell to learn how to run this tool.
AndroidSDK中包含了sqlite3数据库工具,允许你在数据库中,查询表的内容,运行sql命令,执行其他的有用的函数。查看检验远程shell运行sqlite3数据库去学习这些工具的应用。
Using a Network Connection
You can use the network (when it‘s available) to store and retrieve data on your own web-based services. To do network operations, use classes in the following packages:
你可以使用网络取保存和检索数据通过你网络后台的服务。做网络操作,使用下面包中的类。
java.net.*
android.net.*
API翻译 --- Data Storage
标签:
原文地址:http://blog.csdn.net/mikky_android/article/details/51943629