Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> API翻譯 --- Data Storage

API翻譯 --- Data Storage

編輯:關於Android編程

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.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. 資源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: 為了在外部存儲器上讀或寫文件,你的應用需要系統權限。 ...   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開始,讀和寫你應用中的私有目錄不需要讀、寫權限。所以你可以比較低的版本中聲明權限。 android:maxSdkVersion="18" /> ...   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.*  
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved