1. 程式人生 > >Android的數據持久化存儲

Android的數據持久化存儲

class sqli mini service git sta states 並發 sdk

原文: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
一、簡介 Android系統為我們提供了五種數據持久化存儲的方式,以滿足不同的需求。 他們分別是: 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.把數據持久化存儲到手機外部SD卡中。他主要用於非隱秘數據存儲。 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系統中專門提供了Content Providers
這麽一個組件來實現把你的應用程序的數據暴露給別的應用程序,這樣別的應用程序也可以讀寫你的應用程序的數據。 二、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).

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).

To get a SharedPreferences object for your application, use one of two methods:

  • 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.

To write values:

  1. Call edit() to get a SharedPreferences.Editor.
  2. Add values with methods such as putBoolean() and putString().
  3. Commit the new values with commit()

To read values, use SharedPreferences methods such as getBoolean() and getString().

Here is an example that saves a preference for silent keypress mode in a calculator:


publicclassCalcextendsActivity{ publicstaticfinalString PREFS_NAME ="MyPrefsFile"; @Override protectedvoid onCreate(Bundle state){ super.onCreate(state); ... /* Restore preferences*/ SharedPreferences settings = getSharedPreferences(PREFS_NAME,0); boolean silent = settings.getBoolean("silentMode",false); setSilent(silent); } @Override protectedvoid 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(); } }

關於SharedPreferences的更多內容請閱讀《SharedPreferences簡介

三、Internal Storage

3.1、基本知識

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:

  1. Call openFileOutput() with the name of the file and the operating mode. This returns aFileOutputStream.
  2. Write to the file with write().
  3. Close the stream with close().
對於使用Context對象的openFileOutput()openFileInput()來進行數據持久化存儲的這種方式,你的數據文件將存儲在內部存儲空間的/data/data/你的應用程序的包名/files/目錄下,無法指定更深一級的目錄,而且默認是Context.MODE_PRIVATE模式,即別的應用程序不能訪問它。 示例1

String FILENAME ="hello_file"; Stringstring="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. 示例2

String FILENAME ="hello_file"; Stringstring="hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE); fos.write(string.getBytes()); fos.close();

示例3

String FILENAME ="hello_file"; Stringstring="hello world!"; FileOutputStream fos = openFileOutput(FILENAME,Context.MODE_APPEND|Context.MODE_WORLD_READABLE); fos.write(string.getBytes()); fos.close();

註意:在很多手機上,雖然我們使用openFileOutput(FILENAME, Context.MODE_WORLD_READABLE)的方式來創建文件,而且使用ls -l看到該文件對別的應用程序來說其實已經有讀的權限,但是別的應用程序實際上還是無法讀取這些。這時我們需要在創建該文件的應用程序中對getFilesDir()目錄執行"chmod 705"的操作來解決該問題。具體可以參照《Android中一些數據存儲函數的封裝》中的getInternalStorageDirectory()方法。
3.2、Saving cache files

If you‘d like to cache some data, rather than store it persistently, you should use getCacheDir() to open a Filethat represents the internal directory where your application should save temporary cache files.

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.

3.3、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. 3.4、通過JAVA傳統方式訪問 你也可以通過絕對路徑以JAVA傳統方式訪問內部存儲空間。但是以這種方式創建的文件是對私有,創建它的應用程序對該文件是可讀可寫,但是別的應用程序並不能直接訪問它。不是所有的內部存儲空間應用程序都可以訪問,默認情況下只能訪問“/data/data/你的應用程序的包名”這個路徑下的文件。 實際1

File file =newFile("/data/data/"+getPackageName()+"/1.txt"); Log.i(TAG,"path:"+ file.getAbsolutePath()); OutputStreamout=null; try{ out=newBufferedOutputStream(newFileOutputStream(file)); out.write("Hello World".getBytes()); }catch(FileNotFoundException e1){ e1.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }finally{ if(out!=null){ try{ out.close(); }catch(IOException e){ e.printStackTrace(); } } }

運行結果 09-24 22:42:51.468: I/robin(24089): path:/data/data/com.lenovo.robin.test/1.txt 四、External Storage 4.1、簡介

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.

註意:保存在外部存儲(SD卡)上的文件對所有的應用程序都是可讀的,而保存在內部存儲的文件默認對別的應用程序是不可訪問的

Caution: External files can disappear 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.

4.2、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‘s how you can check the availability:

boolean mExternalStorageAvailable =false; boolean mExternalStorageWriteable =false; String state =Environment.getExternalStorageState(); if(Environment.MEDIA_MOUNTED.equals(state)){ /* We can read and write the media*/ mExternalStorageAvailable = mExternalStorageWriteable =true; }elseif(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){ /* We can only read the media*/ mExternalStorageAvailable =true; mExternalStorageWriteable =false; }else{ /* Something else is wrong. It may be one of many other states, but all we need*/ /* to know is we can neither read nor write*/ mExternalStorageAvailable = mExternalStorageWriteable =false; }

This example checks whether the external storage is available to read and write. ThegetExternalStorageState() 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. 4.3、Accessing files on external storage

If you‘re using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application‘s file directory). This method will create the appropriate directory if necessary. By specifying the type of directory, you ensure that the Android‘s media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music). If the user uninstalls your application, this directory and all its contents will be deleted.

If you‘re using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:

/Android/data/<package_name>/files/ 

The <package_name> is your Java-style package name, such as "com.example.android.app". If the user‘s device is running API Level 8 or greater and they uninstall your application, this directory and all its contents will be deleted.

4.4、Saving shared files

f you want to save files that are not specific to your application and that should not be deleted when your application is uninstalled, save them to one of the public directories on the external storage. These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others.

In API Level 8 or greater, usegetExternalStoragePublicDirectory(), passing it the type of public directory you want, such as DIRECTORY_MUSIC,DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others. This method will create the appropriate directory if necessary.

If you‘re using API Level 7 or lower, usegetExternalStorageDirectory() to open a File that represents the root of the external storage, then save your shared files in one of the following directories:

  • Music/ - Media scanner classifies all media found here as user music.
  • Podcasts/ - Media scanner classifies all media found here as a podcast.
  • Ringtones/ - Media scanner classifies all media found here as a ringtone.
  • Alarms/ - Media scanner classifies all media found here as an alarm sound.
  • Notifications/ - Media scanner classifies all media found here as a notification sound.
  • Pictures/ - All photos (excluding those taken with the camera).
  • Movies/ - All movies (excluding those taken with the camcorder).
  • Download/ - Miscellaneous downloads.
4.5、Saving cache files

f you‘re using API Level 8 or greater, use getExternalCacheDir() to open a File that represents the external storage directory where you should save cache files. If the user uninstalls your application, these files will be automatically deleted. However, during the life of your application, you should manage these cache files and remove those that aren‘t needed in order to preserve file space.

If you‘re using API Level 7 or lower, use getExternalStorageDirectory() to open a File that represents the root of the external storage, then write your cache data in the following directory:

/Android/data/<package_name>/cache/ 

The <package_name> is your Java-style package name, such as "com.example.android.app".

4.6、EMMC存儲 很多手機現在都有EMMC存儲(一般是2G),一些手機並沒有掛載在getExternalStorageDirectory()這個節點上(該節點用於掛載外部sdcard了). 而是掛載到如下"/mnt/emmc"的節點上,另外一些手機把EMMC存儲直接掛載到了getExternalStorageDirectory()這個節點上,而對於真正的外部sdcard掛載到了"/mnt/sdcard2"這個節點上。 因此當我們存儲一個文件時首先應該存在getExternalStorageDirectory()這個節點上,其次是"/mnt/sdcard2"這個節點上,再次是"/mnt/emmc",最後才是手機的內部存儲(即“/data”區域)。關於此一些封裝請參照《Android中一些數據存儲函數的封裝》 4.7、一些重要的函數 Android中,關於外部存儲的重要函數,請參考《Android中關於外部存儲的一些重要函數》;關於內部存儲的重要函數,請參考《Android中關於內部存儲的一些重要函數五、數據庫存儲

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.

The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database.

For example:


publicclassDictionaryOpenHelperextendsSQLiteOpenHelper{ privatestaticfinalint DATABASE_VERSION =2; privatestaticfinalString DICTIONARY_TABLE_NAME ="dictionary"; privatestaticfinalString 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 publicvoid 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() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.

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 acontent provider, you must include a unique ID using theBaseColumns._ID constant.

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.

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.

For sample apps that demonstrate how to use SQLite databases in Android, see the Note Pad and Searchable Dictionary applications.

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.

六、網絡存儲

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.*
七、ACache存儲 ACache介紹:ACache類似於SharedPreferences,但是比SharedPreferences功能更加強大,SharedPreferences只能保存一些基本數據類型、Serializable、Bundle等數據。而Acache可以緩存如下數據:普通的字符串、JsonObject、JsonArray、Bitmap、Drawable、序列化的java對象,和 byte數據。主要特色:
  • 1:輕,輕到只有一個JAVA文件。
  • 2:可配置,可以配置緩存路徑,緩存大小,緩存數量等。
  • 3:可以設置緩存超時時間,緩存超時自動失效,並被刪除。
  • 4:支持多進程。
應用場景:
  • 1、替換SharePreference當做配置文件
  • 2、可以緩存網絡請求數據,比如oschina的android客戶端可以緩存http請求的新聞內容,緩存時間假設為1個小時,超時後自動失效,讓客戶端重新請求新的數據,減少客戶端流量,同時減少服務器並發量。
  • 3、您來說...
下載鏈接:https://github.com/yangfuhai/ASimpleCache 八、DiskLruCache硬盤緩存 Google又提供了一套硬盤緩存的解決方案:DiskLruCache(非Google官方編寫,但獲得官方認證)。 更多內容請參考《Android DiskLruCache完全解析,硬盤緩存的最佳方案》 結束

再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!http://www.captainbed.net

Android的數據持久化存儲