內容供應器會管理中央資料存放區的存取權。供應器是 Android 應用程式的一部分,通常會提供專屬 UI 來處理資料。不過,內容供應器主要由其他應用程式使用,這些應用程式會使用供應器用戶端物件存取供應器。供應器和供應器用戶端會共同提供一致的標準資料介面,同時處理處理序間通訊和安全資料存取。
通常,您會在以下兩種情況下使用內容供應器:實作程式碼,以存取其他應用程式中的現有內容供應器,或在應用程式中建立新的內容供應器,與其他應用程式共用資料。
本頁面說明使用現有內容供應器的基本概念。如要瞭解如何在自己的應用程式中實作內容供應器,請參閱「建立內容供應器」。
本主題說明下列事項:
- 內容供應器的運作方式。
- 用於從內容供應器擷取資料的 API。
- 用於在內容供應器中插入、更新或刪除資料的 API。
- 其他可協助與供應商合作的 API 功能。
總覽
內容供應器會以一或多個資料表的形式,向外部應用程式呈現資料,類似於關聯式資料庫中的資料表。資料列代表供應器收集的某種資料例項,而資料列中的每個資料欄則代表為例項收集的個別資料。
內容供應器會協調應用程式中資料儲存層的存取權,以便用於多個不同的 API 和元件。如圖 1 所示,這些包括:
- 與其他應用程式共用應用程式資料存取權
- 將資料傳送至小工具
- 使用
SearchRecentSuggestionsProvider透過搜尋架構傳回應用程式的自訂搜尋建議 - 使用
AbstractThreadedSyncAdapter的實作,將應用程式資料與伺服器同步處理 - 使用
CursorLoader在 UI 中載入資料
圖 1. 內容供應器與其他元件之間的關係。
存取供應商
如要存取內容供應器中的資料,請在應用程式的 Context 中使用 ContentResolver 物件,以用戶端身分與供應器通訊。ContentResolver 物件會與供應器物件通訊,後者是實作 ContentProvider 的類別例項。
供應器物件會接收用戶端的資料要求、執行要求的動作,並傳回結果。這個物件的方法會呼叫供應器物件中名稱相同的方法,而供應器物件是 ContentProvider 的其中一個具體子類別例項。ContentResolver 方法提供永久儲存空間的基本「CRUD」(建立、擷取、更新和刪除) 函式。
從 UI 存取 ContentProvider 的常見模式是使用 CursorLoader 在背景執行非同步查詢。UI 中的 Activity 或 Fragment 會呼叫 CursorLoader 查詢,進而使用 ContentResolver 取得 ContentProvider。
這樣一來,使用者在查詢執行期間仍可使用 UI。這個模式涉及多個不同物件的互動,以及基礎儲存機制,如圖 2 所示。
圖 2. ContentProvider、其他類別和儲存空間之間的互動。
注意:如要存取供應器,應用程式通常必須在資訊清單檔案中要求特定權限。如要進一步瞭解這種開發模式,請參閱「內容供應器權限」一節。
Android 平台內建的其中一個供應器是使用者字典供應器,可儲存使用者想保留的非標準字詞。表 1 說明資料在這個供應商的資料表中可能呈現的樣貌:
表 1:使用者字典表格範例。
| 字詞 | 應用程式編號 | 頻率 | 語言代碼 | _ID |
|---|---|---|---|---|
mapreduce |
user1 | 100 | zh-TW | 1 |
precompiler |
user14 | 200 | fr_FR | 2 |
applet |
user2 | 225 | fr_CA | 3 |
const |
user1 | 255 | pt_BR | 4 |
int |
user5 | 100 | en_UK | 5 |
在表 1 中,每一列代表一個標準字典中找不到的字詞。每個資料欄代表該字詞的一項資料,例如首次出現該字詞的語言代碼。欄標題是儲存在供應商中的欄名稱。舉例來說,如要參照資料列的語言代碼,請參照其 locale 欄。對於這個供應器,_ID 欄會做為供應器自動維護的主鍵欄。
如要從使用者字典供應器取得字詞及其語言代碼清單,請呼叫 ContentResolver.query()。query() 方法會呼叫使用者字典供應器定義的 ContentProvider.query() 方法。以下幾行程式碼顯示 ContentResolver.query() 呼叫:
Kotlin
// Queries the UserDictionary and returns results cursor = contentResolver.query( UserDictionary.Words.CONTENT_URI, // The content URI of the words table projection, // The columns to return for each row selectionClause, // Selection criteria selectionArgs.toTypedArray(), // Selection criteria sortOrder // The sort order for the returned rows )
Java
// Queries the UserDictionary and returns results cursor = getContentResolver().query( UserDictionary.Words.CONTENT_URI, // The content URI of the words table projection, // The columns to return for each row selectionClause, // Selection criteria selectionArgs, // Selection criteria sortOrder); // The sort order for the returned rows
表 2 顯示 query(Uri,projection,selection,selectionArgs,sortOrder) 的引數如何與 SQL SELECT 陳述式相符:
表 2:query()與 SQL 查詢的比較。
query() 引數 |
SELECT 關鍵字/參數 | 附註 |
|---|---|---|
Uri |
FROM table_name |
Uri 會對應至供應器中名為 table_name 的資料表。 |
projection |
col,col,col,... |
projection 是為每個擷取的資料列加入的資料欄陣列。 |
selection |
WHERE col = value |
selection 指定選取資料列的條件。 |
selectionArgs |
沒有完全對應的功能。選取引數會取代選取子句中的 ? 預留位置。 |
|
sortOrder |
ORDER BY col,col,... |
sortOrder 指定資料列在傳回的 Cursor 中顯示的順序。 |
內容 URI
內容 URI 是用於識別供應器中資料的 URI。內容 URI 包含整個供應器的符號名稱 (即「授權單位」),以及指向資料表的名稱 (即「路徑」)。呼叫用戶端方法存取供應器中的資料表時,資料表的內容 URI 是其中一個引數。
在上述程式碼行中,常數 CONTENT_URI 包含使用者字典供應器 Words 資料表的內容 URI。ContentResolver 物件會剖析 URI 的授權,並將授權與已知供應器的系統資料表進行比較,藉此解析供應器。ContentResolver 接著會將查詢引數分派給正確的供應器。
ContentProvider 會使用內容 URI 的路徑部分,選擇要存取的資料表。供應器通常會為其公開的每個資料表提供路徑。
在上述程式碼中,Words 資料表的完整 URI 為:
content://user_dictionary/words
content://字串是「配置」,一律會顯示,並將其識別為內容 URI。user_dictionary字串是供應器的授權。words字串是資料表的路徑。
許多供應器可讓您在 URI 結尾附加 ID 值,藉此存取資料表中的單一資料列。舉例來說,如要從使用者字典供應器擷取 _ID 為 4 的資料列,可以使用以下內容 URI:
Kotlin
val singleUri: Uri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI, 4)
Java
Uri singleUri = ContentUris.withAppendedId(UserDictionary.Words.CONTENT_URI,4);
擷取一組資料列後,如要更新或刪除其中一列,通常會使用 ID 值。
注意:Uri 和 Uri.Builder 類別包含便利的方法,可從字串建構格式正確的 URI 物件。ContentUris 類別包含可將 ID 值附加至 URI 的便利方法。上述程式碼片段使用 withAppendedId(),將 ID 附加至使用者字典供應器內容 URI。
從供應商擷取資料
本節說明如何從供應器擷取資料,並以使用者字典供應器為例。
為求清楚,本節中的程式碼片段會在 UI 執行緒上呼叫 ContentResolver.query()。不過,在實際程式碼中,請在獨立執行緒上以非同步方式執行查詢。您可以使用 CursorLoader 類別,詳情請參閱載入器指南。此外,程式碼行只是程式碼片段。不會顯示完整的應用程式。
如要從供應器擷取資料,請按照下列基本步驟操作:
- 要求提供者的讀取權限。
- 定義將查詢傳送至供應器的程式碼。
要求讀取權限
如要從供應器擷取資料,應用程式必須具備供應器的讀取權限。您無法在執行階段要求這項權限。您必須在資訊清單中使用 <uses-permission> 元素和提供者定義的確切權限名稱,指定您需要這項權限。
在資訊清單中指定這項元素,即代表為應用程式要求這項權限。使用者安裝應用程式時,即代表他們默許這項要求。
如要找出所用供應商的讀取權限確切名稱,以及供應商使用的其他存取權限名稱,請參閱供應商說明文件。
如要進一步瞭解權限在存取供應器時扮演的角色,請參閱「內容供應器權限」一節。
使用者字典供應器會在資訊清單檔案中定義 android.permission.READ_USER_DICTIONARY 權限,因此想要從供應器讀取資料的應用程式必須要求這項權限。
建構查詢
從供應器擷取資料的下一步是建構查詢。下列程式碼片段定義了用於存取使用者字典供應器的變數:
Kotlin
// A "projection" defines the columns that are returned for each row private val mProjection: Array<String> = arrayOf( UserDictionary.Words._ID, // Contract class constant for the _ID column name UserDictionary.Words.WORD, // Contract class constant for the word column name UserDictionary.Words.LOCALE // Contract class constant for the locale column name ) // Defines a string to contain the selection clause private var selectionClause: String? = null // Declares an array to contain selection arguments private lateinit var selectionArgs: Array<String>
Java
// A "projection" defines the columns that are returned for each row String[] mProjection = { UserDictionary.Words._ID, // Contract class constant for the _ID column name UserDictionary.Words.WORD, // Contract class constant for the word column name UserDictionary.Words.LOCALE // Contract class constant for the locale column name }; // Defines a string to contain the selection clause String selectionClause = null; // Initializes an array to contain selection arguments String[] selectionArgs = {""};
下一個程式碼片段說明如何使用 ContentResolver.query(),並以使用者字典供應器為例。供應商用戶端查詢與 SQL 查詢類似,包含一組要傳回的資料欄、一組選取條件和排列順序。
查詢傳回的一組資料欄稱為「投影」,變數為 mProjection。
指定要擷取哪些資料列的運算式會分割成選取子句和選取引數。選取子句是邏輯和布林運算式、資料欄名稱和值的組合。變數為 mSelectionClause。如果指定可替換的參數 ? 而非值,查詢方法會從選取引數陣列 (即變數 mSelectionArgs) 擷取值。
在下一個程式碼片段中,如果使用者未輸入字詞,選取子句會設為 null,而查詢會傳回供應器中的所有字詞。如果使用者輸入字詞,選取子句會設為 UserDictionary.Words.WORD + " = ?",而選取引數陣列的第一個元素會設為使用者輸入的字詞。
Kotlin
/* * This declares a String array to contain the selection arguments. */ private lateinit var selectionArgs: Array<String> // Gets a word from the UI searchString = searchWord.text.toString() // Insert code here to check for invalid or malicious input // If the word is the empty string, gets everything selectionArgs = searchString?.takeIf { it.isNotEmpty() }?.let { selectionClause = "${UserDictionary.Words.WORD} = ?" arrayOf(it) } ?: run { selectionClause = null emptyArray<String>() } // Does a query against the table and returns a Cursor object mCursor = contentResolver.query( UserDictionary.Words.CONTENT_URI, // The content URI of the words table projection, // The columns to return for each row selectionClause, // Either null or the word the user entered selectionArgs, // Either empty or the string the user entered sortOrder // The sort order for the returned rows ) // Some providers return null if an error occurs, others throw an exception when (mCursor?.count) { null -> { /* * Insert code here to handle the error. Be sure not to use the cursor! * You might want to call android.util.Log.e() to log this error. */ } 0 -> { /* * Insert code here to notify the user that the search is unsuccessful. This isn't * necessarily an error. You might want to offer the user the option to insert a new * row, or re-type the search term. */ } else -> { // Insert code here to do something with the results } }
Java
/* * This defines a one-element String array to contain the selection argument. */ String[] selectionArgs = {""}; // Gets a word from the UI searchString = searchWord.getText().toString(); // Remember to insert code here to check for invalid or malicious input // If the word is the empty string, gets everything if (TextUtils.isEmpty(searchString)) { // Setting the selection clause to null returns all words selectionClause = null; selectionArgs[0] = ""; } else { // Constructs a selection clause that matches the word that the user entered selectionClause = UserDictionary.Words.WORD + " = ?"; // Moves the user's input string to the selection arguments selectionArgs[0] = searchString; } // Does a query against the table and returns a Cursor object mCursor = getContentResolver().query( UserDictionary.Words.CONTENT_URI, // The content URI of the words table projection, // The columns to return for each row selectionClause, // Either null or the word the user entered selectionArgs, // Either empty or the string the user entered sortOrder); // The sort order for the returned rows // Some providers return null if an error occurs, others throw an exception if (null == mCursor) { /* * Insert code here to handle the error. Be sure not to use the cursor! You can * call android.util.Log.e() to log this error. * */ // If the Cursor is empty, the provider found no matches } else if (mCursor.getCount() < 1) { /* * Insert code here to notify the user that the search is unsuccessful. This isn't necessarily * an error. You can offer the user the option to insert a new row, or re-type the * search term. */ } else { // Insert code here to do something with the results }
這項查詢類似於下列 SQL 陳述式:
SELECT _ID, word, locale FROM words WHERE word = <userinput> ORDER BY word ASC;
在這個 SQL 陳述式中,系統會使用實際的資料欄名稱,而非合約類別常數。
防範惡意輸入
如果內容供應器管理的資料位於 SQL 資料庫,將外部不受信任的資料納入原始 SQL 陳述式,可能會導致 SQL 注入。
請考慮下列選取子句:
Kotlin
// Constructs a selection clause by concatenating the user's input to the column name var selectionClause = "var = $mUserInput"
Java
// Constructs a selection clause by concatenating the user's input to the column name String selectionClause = "var = " + userInput;
如果這樣做,使用者可能會將惡意 SQL 串連至您的 SQL 陳述式。
舉例來說,使用者可以為 mUserInput 輸入「nothing; DROP TABLE *;」,這會產生選取子句 var = nothing; DROP TABLE *;。
由於選取子句會視為 SQL 陳述式,因此除非供應器設定為擷取 SQL 注入嘗試,否則供應器可能會清除基礎 SQLite 資料庫中的所有資料表。
為避免這個問題,請使用以 ? 做為可替換參數的選取子句,並搭配一組另外的選取參數。這樣一來,使用者輸入內容就會直接繫結至查詢,而不會解讀為 SQL 陳述式的一部分。由於系統不會將使用者輸入內容視為 SQL,因此使用者無法插入惡意 SQL。請改用以下選取子句,不要使用串連來納入使用者輸入內容:
Kotlin
// Constructs a selection clause with a replaceable parameter var selectionClause = "var = ?"
Java
// Constructs a selection clause with a replaceable parameter String selectionClause = "var = ?";
請按照下列方式設定選取引數陣列:
Kotlin
// Defines a mutable list to contain the selection arguments var selectionArgs: MutableList<String> = mutableListOf()
Java
// Defines an array to contain the selection arguments String[] selectionArgs = {""};
在選取引數陣列中輸入值,如下所示:
Kotlin
// Adds the user's input to the selection argument selectionArgs += userInput
Java
// Sets the selection argument to the user's input selectionArgs[0] = userInput;
即使供應器並非以 SQL 資料庫為基礎,指定選取項目的首選方式仍是使用 ? 做為可替換參數的選取子句,以及選取引數陣列。
顯示查詢結果
ContentResolver.query() 用戶端方法一律會傳回 Cursor,其中包含查詢投影為符合查詢選取條件的資料列指定的資料欄。Cursor 物件可讓您隨機讀取其中包含的資料列和資料欄。
使用 Cursor 方法,您可以疊代結果中的資料列、判斷每個資料欄的資料類型、從資料欄中取得資料,以及檢查結果的其他屬性。
部分 Cursor 實作會在供應商資料變更時自動更新物件、在 Cursor 變更時觸發觀察器物件中的方法,或同時執行這兩項操作。
注意:供應器可以根據查詢物件的性質,限制資料欄的存取權。舉例來說,聯絡人供應程式會限制某些資料欄的存取權,僅允許同步轉換介面存取,因此不會將這些資料欄傳回活動或服務。
如果沒有任何資料列符合選取條件,供應器會傳回 Cursor.getCount() 為 0 的 Cursor 物件,也就是空白游標。
如果發生內部錯誤,查詢結果會因特定供應商而異。可能會傳回 null,或擲回 Exception。
由於 Cursor 是資料列清單,因此顯示 Cursor 內容的理想方式是使用 SimpleCursorAdapter 將其連結至 ListView。
下列程式碼片段接續了先前的程式碼片段。它會建立包含查詢擷取的 Cursor 的 SimpleCursorAdapter 物件,並將此物件設定為 ListView 的轉接器。
Kotlin
// Defines a list of columns to retrieve from the Cursor and load into an output row val wordListColumns : Array<String> = arrayOf( UserDictionary.Words.WORD, // Contract class constant containing the word column name UserDictionary.Words.LOCALE // Contract class constant containing the locale column name ) // Defines a list of View IDs that receive the Cursor columns for each row val wordListItems = intArrayOf(R.id.dictWord, R.id.locale) // Creates a new SimpleCursorAdapter cursorAdapter = SimpleCursorAdapter( applicationContext, // The application's Context object R.layout.wordlistrow, // A layout in XML for one row in the ListView mCursor, // The result from the query wordListColumns, // A string array of column names in the cursor wordListItems, // An integer array of view IDs in the row layout 0 // Flags (usually none are needed) ) // Sets the adapter for the ListView wordList.setAdapter(cursorAdapter)
Java
// Defines a list of columns to retrieve from the Cursor and load into an output row String[] wordListColumns = { UserDictionary.Words.WORD, // Contract class constant containing the word column name UserDictionary.Words.LOCALE // Contract class constant containing the locale column name }; // Defines a list of View IDs that receive the Cursor columns for each row int[] wordListItems = { R.id.dictWord, R.id.locale}; // Creates a new SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter( getApplicationContext(), // The application's Context object R.layout.wordlistrow, // A layout in XML for one row in the ListView mCursor, // The result from the query wordListColumns, // A string array of column names in the cursor wordListItems, // An integer array of view IDs in the row layout 0); // Flags (usually none are needed) // Sets the adapter for the ListView wordList.setAdapter(cursorAdapter);
注意:如要使用 Cursor 備份 ListView,游標必須包含名為 _ID 的資料欄。因此,即使 ListView 未顯示 Words 資料表的 _ID 資料欄,先前顯示的查詢仍會擷取該資料欄。這項限制也說明瞭為什麼大多數供應商的每個資料表都有 _ID 欄。
從查詢結果取得資料
除了顯示查詢結果外,您還可以使用這些結果執行其他工作。舉例來說,您可以從使用者字典供應器擷取拼字,然後在其他供應器中查詢。方法是疊代 Cursor 中的資料列,如以下範例所示:
Kotlin
/* * Only executes if the cursor is valid. The User Dictionary Provider returns null if * an internal error occurs. Other providers might throw an Exception instead of returning null. */ mCursor?.apply { // Determine the column index of the column named "word" val index: Int = getColumnIndex(UserDictionary.Words.WORD) /* * Moves to the next row in the cursor. Before the first movement in the cursor, the * "row pointer" is -1, and if you try to retrieve data at that position you get an * exception. */ while (moveToNext()) { // Gets the value from the column newWord = getString(index) // Insert code here to process the retrieved word ... // End of while loop } }
Java
// Determine the column index of the column named "word" int index = mCursor.getColumnIndex(UserDictionary.Words.WORD); /* * Only executes if the cursor is valid. The User Dictionary Provider returns null if * an internal error occurs. Other providers might throw an Exception instead of returning null. */ if (mCursor != null) { /* * Moves to the next row in the cursor. Before the first movement in the cursor, the * "row pointer" is -1, and if you try to retrieve data at that position you get an * exception. */ while (mCursor.moveToNext()) { // Gets the value from the column newWord = mCursor.getString(index); // Insert code here to process the retrieved word ... // End of while loop } } else { // Insert code here to report an error if the cursor is null or the provider threw an exception }
Cursor 實作包含多個「get」方法,用於從物件擷取不同類型的資料。舉例來說,上述程式碼片段使用的是 getString()。此外,這些物件也提供 getType() 方法,可傳回表示資料欄資料類型的值。
釋出查詢結果資源
如果不再需要 Cursor 物件,請務必將其關閉,以便盡快釋出相關資源。您可以呼叫 close(),或在 Java 程式設計語言中使用 try-with-resources 陳述式,或在 Kotlin 程式設計語言中使用 use() 函式。
內容供應器權限
供應器的應用程式可以指定其他應用程式必須具備的權限,才能存取供應器的資料。這些權限可讓使用者瞭解應用程式嘗試存取的資料。根據供應器的需求,其他應用程式會要求存取供應器所需的權限。使用者會在安裝應用程式時看到要求的權限。
如果供應器的應用程式未指定任何權限,其他應用程式就無法存取供應器的資料,除非供應器已匯出。此外,無論指定權限為何,供應器應用程式中的元件一律具有完整的讀取和寫入權限。
使用者字典供應器需要 android.permission.READ_USER_DICTIONARY 權限,才能從中擷取資料。供應者有獨立的 android.permission.WRITE_USER_DICTIONARY 權限,可用於插入、更新或刪除資料。
如要取得存取供應器所需的權限,應用程式會在其資訊清單檔案中使用 <uses-permission> 元素要求權限。Android 套件管理員安裝應用程式時,使用者必須核准應用程式要求的所有權限。如果使用者核准,Package Manager 就會繼續安裝。如果使用者未核准,套件管理員就會停止安裝。
下列 <uses-permission> 元素範例會要求使用者字典供應器的讀取權限:
<uses-permission android:name="android.permission.READ_USER_DICTIONARY">如要進一步瞭解權限對供應器存取權的影響,請參閱「安全性提示」。
插入、更新及刪除資料
就像從供應器擷取資料一樣,您也可以使用供應器用戶端與供應器 ContentProvider 之間的互動來修改資料。您可以使用傳遞至 ContentProvider 對應方法的引數,呼叫 ContentResolver 的方法。供應器和供應器用戶端會自動處理安全性和處理序間通訊。
插入資料
如要將資料插入供應器,請呼叫 ContentResolver.insert() 方法。這個方法會在供應器中插入新資料列,並傳回該資料列的內容 URI。下列程式碼片段說明如何將新字詞插入使用者字典供應器:
Kotlin
// Defines a new Uri object that receives the result of the insertion lateinit var newUri: Uri ... // Defines an object to contain the new values to insert val newValues = ContentValues().apply { /* * Sets the values of each column and inserts the word. The arguments to the "put" * method are "column name" and "value". */ put(UserDictionary.Words.APP_ID, "example.user") put(UserDictionary.Words.LOCALE, "en_US") put(UserDictionary.Words.WORD, "insert") put(UserDictionary.Words.FREQUENCY, "100") } newUri = contentResolver.insert( UserDictionary.Words.CONTENT_URI, // The UserDictionary content URI newValues // The values to insert )
Java
// Defines a new Uri object that receives the result of the insertion Uri newUri; ... // Defines an object to contain the new values to insert ContentValues newValues = new ContentValues(); /* * Sets the values of each column and inserts the word. The arguments to the "put" * method are "column name" and "value". */ newValues.put(UserDictionary.Words.APP_ID, "example.user"); newValues.put(UserDictionary.Words.LOCALE, "en_US"); newValues.put(UserDictionary.Words.WORD, "insert"); newValues.put(UserDictionary.Words.FREQUENCY, "100"); newUri = getContentResolver().insert( UserDictionary.Words.CONTENT_URI, // The UserDictionary content URI newValues // The values to insert );
新資料列的資料會進入單一 ContentValues 物件,其形式與單列游標類似。這個物件中的資料欄不一定要有相同的資料類型,如果您完全不想指定值,可以使用 ContentValues.putNull() 將資料欄設為 null。
上述程式碼片段不會新增 _ID 資料欄,因為系統會自動維護這個資料欄。供應器會為新增的每一列指派不重複的 _ID 值。供應器通常會使用這個值做為資料表的主鍵。
newUri 中傳回的內容 URI 會以下列格式識別新加入的資料列:
content://user_dictionary/words/<id_value>
<id_value> 是新資料列的 _ID 內容。大多數供應器都能自動偵測這種形式的內容 URI,然後對該特定資料列執行要求的作業。
如要從傳回的 Uri 取得 _ID 的值,請呼叫 ContentUris.parseId()。
更新資料
如要更新資料列,請使用含有更新值的 ContentValues 物件 (與插入資料列時相同),並指定選取條件 (與查詢時相同)。您使用的用戶端方法是 ContentResolver.update()。您只需要為要更新的資料欄,將值新增至 ContentValues 物件。如要清除資料欄內容,請將值設為 null。
下列程式碼片段會將語言代碼為 "en" 的所有資料列變更為語言代碼為 null。傳回值是更新的資料列數量。
Kotlin
// Defines an object to contain the updated values val updateValues = ContentValues().apply { /* * Sets the updated value and updates the selected words. */ putNull(UserDictionary.Words.LOCALE) } // Defines selection criteria for the rows you want to update val selectionClause: String = UserDictionary.Words.LOCALE + "LIKE ?" val selectionArgs: Array<String> = arrayOf("en_%") // Defines a variable to contain the number of updated rows var rowsUpdated: Int = 0 ... rowsUpdated = contentResolver.update( UserDictionary.Words.CONTENT_URI, // The UserDictionary content URI updateValues, // The columns to update selectionClause, // The column to select on selectionArgs // The value to compare to )
Java
// Defines an object to contain the updated values ContentValues updateValues = new ContentValues(); // Defines selection criteria for the rows you want to update String selectionClause = UserDictionary.Words.LOCALE + " LIKE ?"; String[] selectionArgs = {"en_%"}; // Defines a variable to contain the number of updated rows int rowsUpdated = 0; ... /* * Sets the updated value and updates the selected words. */ updateValues.putNull(UserDictionary.Words.LOCALE); rowsUpdated = getContentResolver().update( UserDictionary.Words.CONTENT_URI, // The UserDictionary content URI updateValues, // The columns to update selectionClause, // The column to select on selectionArgs // The value to compare to );
呼叫 ContentResolver.update() 時,請清理使用者輸入內容。詳情請參閱「防範惡意輸入」一節。
刪除資料
刪除資料列與擷取資料列資料類似。您需要指定要刪除的資料列選取條件,用戶端方法則會傳回刪除的資料列數量。下列程式碼片段會刪除應用程式 ID 與 "user" 相符的資料列。這個方法會傳回已刪除的資料列數量。
Kotlin
// Defines selection criteria for the rows you want to delete val selectionClause = "${UserDictionary.Words.APP_ID} LIKE ?" val selectionArgs: Array<String> = arrayOf("user") // Defines a variable to contain the number of rows deleted var rowsDeleted: Int = 0 ... // Deletes the words that match the selection criteria rowsDeleted = contentResolver.delete( UserDictionary.Words.CONTENT_URI, // The UserDictionary content URI selectionClause, // The column to select on selectionArgs // The value to compare to )
Java
// Defines selection criteria for the rows you want to delete String selectionClause = UserDictionary.Words.APP_ID + " LIKE ?"; String[] selectionArgs = {"user"}; // Defines a variable to contain the number of rows deleted int rowsDeleted = 0; ... // Deletes the words that match the selection criteria rowsDeleted = getContentResolver().delete( UserDictionary.Words.CONTENT_URI, // The UserDictionary content URI selectionClause, // The column to select on selectionArgs // The value to compare to );
呼叫 ContentResolver.delete() 時,請清理使用者輸入內容。如要進一步瞭解這項功能,請參閱「防範惡意輸入」一節。
供應商資料類型
內容供應器可提供多種資料類型。使用者字典供應器僅提供文字,但供應器也可以提供下列格式:
- integer
- 長整數 (long)
- 浮點
- 長浮點 (雙精度)
供應器經常使用的另一種資料類型是二進位大型物件 (BLOB),以 64 KB 位元組陣列的形式實作。您可以查看 Cursor 類別的「get」方法,瞭解可用的資料類型。
供應商文件中通常會列出各欄的資料類型。
使用者字典供應器的資料類型列在合約類別 UserDictionary.Words 的參考文件中。合約類別請參閱「合約類別」一節。您也可以呼叫 Cursor.getType() 來判斷資料類型。
供應器也會為定義的每個內容 URI 維護 MIME 資料類型資訊。您可以使用 MIME 類型資訊,瞭解應用程式是否能處理供應器提供的資料,或根據 MIME 類型選擇處理類型。如果供應器包含複雜的資料結構或檔案,通常需要使用 MIME 類型。
舉例來說,聯絡人供應程式中的 ContactsContract.Data 資料表會使用 MIME 類型,標示儲存在各列的聯絡資料類型。如要取得與內容 URI 對應的 MIME 類型,請呼叫 ContentResolver.getType()。
「MIME 類型參考資料」一節說明標準和自訂 MIME 類型的語法。
其他供應商存取方式
在應用程式開發中,有三種重要的供應器存取替代形式:
-
批次存取:您可以使用
ContentProviderOperation類別中的方法建立一批存取呼叫,然後使用ContentResolver.applyBatch()套用這些呼叫。 -
非同步查詢:在獨立執行緒中執行查詢。您可以使用
CursorLoader物件。載入器指南中的範例說明瞭如何執行這項操作。 - 使用意圖存取資料:雖然您無法直接將意圖傳送給供應器,但可以將意圖傳送給供應器的應用程式,這通常是修改供應器資料的最佳方式。
以下各節將說明如何使用意圖進行批次存取和修改。
批次存取
批次存取供應器適用於插入大量資料列、在同一個方法呼叫中插入多個資料表的資料列,以及一般情況下,跨程序邊界執行一組作業做為交易,稱為「原子作業」。
如要以批次模式存取供應器,請建立 ContentProviderOperation 物件陣列,然後使用 ContentResolver.applyBatch() 將這些物件調度至內容供應器。您需要將內容供應器的授權傳遞至這個方法,而非特定內容 URI。
這樣一來,陣列中的每個 ContentProviderOperation 物件都能對不同的資料表執行。呼叫 ContentResolver.applyBatch() 會傳回結果陣列。
ContactsContract.RawContacts 合約類別的說明包含示範批次插入的程式碼片段。
使用意圖存取資料
意圖可提供內容供應器的間接存取權。即使應用程式沒有存取權限,您也可以讓使用者存取供應器中的資料,方法是從具有權限的應用程式取得結果意圖,或啟用具有權限的應用程式,讓使用者在其中執行工作。
取得臨時權限
即使您沒有適當的存取權限,也可以存取內容供應器中的資料,方法是將意圖傳送至具有權限的應用程式,並接收包含 URI 權限的結果意圖。這些是特定內容 URI 的權限,會持續到接收權限的活動結束為止。具有永久權限的應用程式會透過在結果意圖中設定標記,授予暫時權限:
注意:這些旗標不會授予一般讀取或寫入權限,給內容 URI 中包含授權的供應器。存取權僅限於 URI 本身。
將內容 URI 傳送至其他應用程式時,請至少加入其中一個旗標。這些標記會為任何接收意圖且指定 Android 11 (API 級別 30) 以上版本的應用程式提供下列功能:
- 讀取或寫入內容 URI 代表的資料 (視意圖中的旗標而定)。
- 查看含有與 URI 授權相符的內容供應器的應用程式套件。傳送意圖的應用程式和包含內容供應器的應用程式可能是兩個不同的應用程式。
供應器會在資訊清單中定義內容 URI 的 URI 權限,方法是使用 <provider> 元素的 android:grantUriPermissions 屬性,以及 <provider> 元素的 <grant-uri-permission> 子項元素。如要進一步瞭解 URI 權限機制,請參閱「Android 中的權限」指南。
舉例來說,即使您沒有 READ_CONTACTS 權限,也可以在聯絡人供應程式中擷取聯絡人的資料。舉例來說,如果應用程式會在聯絡人生日當天傳送電子賀卡,您可能就會想這麼做。請讓使用者控管應用程式使用的聯絡人,而不是要求 READ_CONTACTS,這會讓您存取使用者的所有聯絡人和所有資訊。方法如下:
-
在應用程式中,使用
startActivityForResult()方法傳送包含ACTION_PICK動作和「聯絡人」MIME 類型CONTENT_ITEM_TYPE的意圖。 - 由於這項意圖與「聯絡人」應用程式「選取」活動的意圖篩選器相符,因此該活動會移至前景。
-
在選取活動中,使用者選取要更新的聯絡人。發生這種情況時,選取活動會呼叫
setResult(resultcode, intent),設定要傳回應用程式的意圖。意圖包含使用者所選聯絡人的內容 URI 和「額外」標記FLAG_GRANT_READ_URI_PERMISSION。這些旗標會授予 URI 權限給應用程式,讓應用程式讀取內容 URI 指向的聯絡人資料。接著,選取活動會呼叫finish(),將控制權交回給應用程式。 -
活動返回前景,系統呼叫活動的
onActivityResult()方法。這個方法會接收「聯絡人」應用程式中選取活動建立的結果意圖。 - 有了結果意圖中的內容 URI,您就能從聯絡人供應程式讀取聯絡人資料,即使您未在資訊清單中要求供應程式的永久讀取權限也沒問題。接著,您可以取得聯絡人的生日資訊或電子郵件地址,然後傳送電子賀卡。
使用其他應用程式
如果想讓使用者修改您沒有存取權限的資料,另一個方法是啟用具有權限的應用程式,讓使用者在該應用程式中執行操作。
舉例來說,日曆應用程式接受 ACTION_INSERT 意圖,可讓您啟用應用程式的插入 UI。您可以在這個意圖中傳遞「額外」資料,應用程式會使用這些資料預先填入 UI。由於週期性活動的語法較為複雜,因此將活動插入日曆供應器的首選方式是使用 ACTION_INSERT 啟用日曆應用程式,然後讓使用者在該處插入活動。
使用輔助應用程式顯示資料
如果您的應用程式確實具備存取權限,您仍可使用意圖在其他應用程式中顯示資料。舉例來說,日曆應用程式接受 ACTION_VIEW 意圖,可顯示特定日期或活動。這樣一來,您就不必建立自己的 UI,也能顯示日曆資訊。
如要進一步瞭解這項功能,請參閱「日曆供應商總覽」。
您傳送意圖的應用程式不一定要與供應商相關聯。舉例來說,您可以從聯絡人供應程式擷取聯絡人,然後將包含聯絡人圖片內容 URI 的 ACTION_VIEW 意圖傳送至圖片檢視器。
合約類別
合約類別定義的常數,可協助應用程式處理內容 URI、資料欄名稱、意圖動作,以及內容供應器的其他功能。合約類別不會自動包含在供應器中。供應商的開發人員必須定義這些內容,然後提供給其他開發人員。Android 平台隨附的許多供應器在 android.provider 套件中都有對應的合約類別。
舉例來說,使用者字典供應器具有合約類別 UserDictionary,其中包含內容 URI 和資料欄名稱常數。Words 資料表的內容 URI 定義在常數 UserDictionary.Words.CONTENT_URI 中。UserDictionary.Words 類別也包含資料欄名稱常數,用於本指南的範例程式碼片段。舉例來說,查詢投影可以定義如下:
Kotlin
val projection : Array<String> = arrayOf( UserDictionary.Words._ID, UserDictionary.Words.WORD, UserDictionary.Words.LOCALE )
Java
String[] projection = { UserDictionary.Words._ID, UserDictionary.Words.WORD, UserDictionary.Words.LOCALE };
另一個合約類別是聯絡人供應程式的 ContactsContract。這個類別的參考文件包含程式碼片段範例。其中一個子類別 ContactsContract.Intents.Insert 是合約類別,包含意圖和意圖資料的常數。
MIME 類型參考資料
內容供應器可以傳回標準 MIME 媒體類型、自訂 MIME 類型字串,或兩者皆傳回。
MIME 類型的格式如下:
type/subtype
舉例來說,常見的 MIME 類型 text/html 具有 text 類型和 html 子類型。如果供應器針對 URI 傳回這個類型,表示使用該 URI 的查詢會傳回包含 HTML 代碼的文字。
自訂 MIME 類型字串 (也稱為「供應商專屬」MIME 類型) 具有更複雜的 type 和 subtype 值。如果是多列,類型值一律如下:
vnd.android.cursor.dir
如果是單一資料列,類型值一律如下:
vnd.android.cursor.item
subtype 為供應商專用功能,Android 內建供應商通常具有簡單的子類型。舉例來說,當聯絡人應用程式為電話號碼建立資料列時,會在資料列中設定下列 MIME 類型:
vnd.android.cursor.item/phone_v2
子類型值為 phone_v2。
其他供應商開發人員可以根據供應商的授權和資料表名稱,建立自己的子類型模式。舉例來說,假設供應器包含火車時刻表。供應器的授權單位為 com.example.trains,其中包含 Line1、Line2 和 Line3 資料表。為因應 Line1 資料表的下列內容 URI:
content://com.example.trains/Line1
供應器會傳回下列 MIME 類型:
vnd.android.cursor.dir/vnd.example.line1
針對 Line2 資料表第 5 列的下列內容 URI:
content://com.example.trains/Line2/5
供應器會傳回下列 MIME 類型:
vnd.android.cursor.item/vnd.example.line2
大多數內容供應器會為使用的 MIME 類型定義合約類別常數。舉例來說,聯絡人供應程式合約類別 ContactsContract.RawContacts 會為單一原始聯絡人資料列的 MIME 類型定義常數 CONTENT_ITEM_TYPE。
如要瞭解單一資料列的內容 URI,請參閱「內容 URI」一節。