Android數(shù)據(jù)存儲訪問機制
大家在開發(fā)Android操作系統(tǒng)的時候,可能會經(jīng)常碰到關(guān)于數(shù)據(jù)存儲方面的一些操作。在這里我們會為大家詳細介紹一下有關(guān)Android數(shù)據(jù)存儲的一些基本概念以及應(yīng)用技巧。在Android 系統(tǒng)中,所有應(yīng)用程序數(shù)據(jù)都是私有的,任何其他應(yīng)用程序都是無法訪問的。#t#
1. 如何使得應(yīng)用程序的數(shù)據(jù)可以被外部訪問呢?
答案是使用android 的content provider 接口,content provider 可以使應(yīng)用程序的私有數(shù)據(jù)暴露給其它application.
有兩種選擇來暴露application data,一種是建立自己的content provider,另外一種是使用已有的content provider前提是數(shù)據(jù)類型一致。
2. Android數(shù)據(jù)存儲的數(shù)據(jù)類型
Android 提供了一系列的 content type. 包括image, audio, and video files and personal contact information 等等.
3. Android數(shù)據(jù)存儲機制
Android 提供了存儲和獲取數(shù)據(jù)的以下幾種機制
3.1. Preference
Preference 提供了一種輕量級的存取機制,主要是可以通過關(guān)鍵字讀取和存儲某個Preference value.
比如載系統(tǒng)啟動的時候得到上次系統(tǒng)退出時候保存的值。
- view plaincopy to clipboardprint?
- . . .
- 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();
- // Save user preferences. We need an Editor object to
- // make changes. All objects are from android.context.Context
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putBoolean("silentMode", mSilentMode);
- // Don't forget to commit your edits!!!
- editor.commit();
- }
- . . .
- 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();
- // Save user preferences. We need an Editor object to
- // make changes. All objects are from android.context.Context
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- SharedPreferences.Editor editor = settings.edit();
- editor.putBoolean("silentMode", mSilentMode);
- // Don't forget to commit your edits!!!
- editor.commit();
- }
3.2. Files
通過Android數(shù)據(jù)存儲中的File機制你可以直接存儲一個文件到你手機文件系統(tǒng)路徑比如SD卡中。
需要注意的是 , 默認情況下存儲的文件是不可以被其他application是訪問的 !!
Context.openFileInput() 返回java的標準文件輸入對象。
Context.openFileOutput() 返回java的標準文件輸出對象。
3.3. Databases.
Android 使用 SQLite 數(shù)據(jù)庫。
可以通過調(diào)用SQLiteDatabase.create() and 以及子類 SQLiteOpenHelper.
Android 還提供了sqlite3 database tool, 你可以通過這個工具像MySQL tool那樣來直接訪問,修改數(shù)據(jù)庫
3.4. Network.
***你也可以通過網(wǎng)絡(luò)來存儲數(shù)據(jù),使用下面兩個包的java class.
- java.net.*
- android.net.*
Android數(shù)據(jù)存儲的相關(guān)應(yīng)用就為大家介紹到這里。






