Content provider 基础知识

content provider 管理对中央存储库的访问。提供程序是 Android 应用的一部分,通常提供自己的界面来处理数据。不过,内容提供程序主要供其他应用使用,这些应用使用提供程序客户端对象来访问提供程序。提供程序和提供程序客户端共同提供一个一致的标准数据接口,该接口还可以处理进程间通信和安全数据访问。

通常,您会在以下两种情况下使用 content provider:实现代码以访问其他应用中的现有 content provider,或在您的应用中创建新的 content provider 以与其他应用共享数据。

本页介绍了使用现有 content provider 的基础知识。如需了解如何在您自己的应用中实现 content provider,请参阅创建 content provider。

本主题介绍以下内容:

  • 内容提供程序的工作方式。
  • 用于从内容提供程序检索数据的 API。
  • 用于在内容提供程序中插入、更新或删除数据的 API。
  • 其他有助于使用内容提供程序的 API 功能。

概览

内容提供程序以一个或多个表的形式将数据呈现给外部应用,这些表与关系型数据库中的表类似。行表示提供程序收集的某种类型数据的实例,行中的每一列表示为一个实例所收集的单个数据。

content provider 可协调对应用中数据存储区的访问,以支持多种不同的 API 和组件。如图 1 所示,这些功能包括:

内容提供程序与其他组件的关系。

图 1. content provider 与其他组件之间的关系。

访问提供商

如需访问内容提供程序中的数据,您可以客户端的形式使用应用的 Context 中的 ContentResolver 对象与提供程序进行通信。ContentResolver 对象与提供程序对象(实现 ContentProvider 的类的实例)进行通信。

提供程序对象从客户端接收数据请求、执行请求的操作并返回结果。此对象具有在提供程序对象(ContentProvider 的某个具体子类的实例)中调用同名方法的方法。ContentResolver 方法提供永久性存储的基本“CRUD”(创建、检索、更新和删除)功能。

从界面访问 ContentProvider 的常用模式是使用 CursorLoader 在后台运行异步查询。界面中的 Activity 或 Fragment 会调用 CursorLoader 来执行查询,后者又会使用 ContentResolver 获取 ContentProvider。

这样,在查询运行期间,界面仍可供用户使用。如图 2 所示,此模式涉及很多不同对象的交互,以及底层存储机制。

内容提供程序、其他类和存储空间之间的交互。

图 2. ContentProvider、其他类和存储之间的交互。

注意:如需访问提供程序,您的应用通常需要在其清单文件中请求特定权限。Content Provider 权限部分对此开发模式进行了更详细的说明。

Android 平台中的一个内置提供程序是用户字典提供程序,它用于存储用户想要保留的非标准字词。此提供程序表中的数据可能如表 1 所示:

表 1:用户字典表示例。

字词 应用 ID 频率 语言区域 _ID
mapreduce user1 100 zh_CN 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 将是其参数之一。

在前面的代码行中,常量 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。

从提供程序检索数据

本部分将以用户字典提供程序为例,介绍如何从提供程序中检索数据。

为清楚起见,本部分中的代码段在界面线程上调用 ContentResolver.query()。不过,在实际代码中,请在单独的线程上异步执行查询。您可以使用 CursorLoader 类,加载器指南中对此类进行了更详细的介绍。此外,这些代码行只是代码段。它们不会显示完整的应用。

如需从提供程序检索数据,请按照以下基本步骤执行操作:

  1. 请求提供程序的读取访问权限。
  2. 定义将查询发送至提供程序的代码。

请求读取访问权限

如需从提供程序检索数据,您的应用需要对该提供程序具有读取访问权限。您无法在运行时请求此权限。相反,您必须使用 <uses-permission> 元素和提供程序定义的确切权限名称,在清单中指定您需要此权限。

当您在清单中指定此元素时,即表示您在为应用请求此权限。用户在安装您的应用时,他们会隐式允许此请求。

如需为您正在使用的提供程序找出读取访问权限的准确名称,以及提供程序所用的其他访问权限的名称,请查看提供程序的文档。

Content Provider 权限部分更详细地介绍了权限在访问提供程序时所起的作用。

用户字典提供程序在其清单文件中定义了权限 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 语句中,会使用实际的列名称而非协定类常量。

防范恶意输入

如果 content provider 管理的数据位于 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 语句,因此这可能会导致提供程序清除底层 SQLite 数据库中的所有表,除非提供程序设置为捕获 SQL 注入尝试。

为了避免此问题,请使用将 ? 作为可替换参数的选择子句,以及单独的选择参数数组。这样,用户输入会直接绑定到查询,而不会被解释为 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 发生更改时,会触发观察器对象中的方法,或同时执行这两项操作。

注意:提供程序可以根据发出查询的对象的性质来限制对列的访问。例如,联系人提供程序会限制某些列对同步适配器的访问权限,因此不会将这些列返回给 activity 或服务。

如果没有行与选择条件匹配,则提供程序会返回一个 Cursor.getCount() 为 0 的 Cursor 对象,即空游标。

如果出现内部错误,查询结果视具体提供程序而定。它可能会返回 null,也可能会抛出 Exception。

由于 Cursor 是一个行列表,因此显示 Cursor 内容的一种好方法是使用 SimpleCursorAdapter 将其关联到 ListView。

以下代码段承接上个代码段的代码。它会创建一个 SimpleCursorAdapter 对象,其中包含查询检索到的 Cursor,并将此对象设置为 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,Cursor 必需包含名为 _ID 的列。因此,前面显示的查询会检索 Words 表的 _ID 列,即使 ListView 未显示该列也是如此。 此限制也解释了为什么大多数提供程序都为其每个表提供一个 _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 实现包含多个“获取”方法,用于从对象中检索不同类型的数据。例如,上一个代码段使用 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 对象中,该对象在形式上与单行 Cursor 类似。此对象中的列无需拥有相同的数据类型,如果您不想指定值,则可以使用 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() 时,请对用户输入进行排查。如需了解详情,请参阅防范恶意输入部分。

提供方数据类型

内容提供程序可以提供多种不同的数据类型。用户字典提供程序仅提供文本,但提供程序也能提供以下格式:

  • 整数
  • 长整型 (long)
  • 浮点型
  • 长浮点型 (double)

提供程序经常使用的另一种数据类型是二进制大型对象 (BLOB),它作为 64 KB 字节数组实现。您可以查看 Cursor 类的“获取”方法,从而查看可用数据类型。

提供程序文档通常都会列出其每个列的数据类型。用户字典提供程序的数据类型列在其协定类 UserDictionary.Words 的参考文档中。协定类部分介绍了协定类。 您也可通过调用 Cursor.getType() 确定数据类型。

提供程序还会为其定义的每个内容 URI 维护 MIME(多用途互联网邮件扩展)数据类型信息。您可以使用 MIME 类型信息来确定应用是否可以处理提供程序提供的数据,或根据 MIME 类型选择处理类型。当您使用的提供程序包含复杂的数据结构或文件时,通常需要 MIME 类型。

例如,联系人提供程序中的 ContactsContract.Data 表会使用 MIME 类型标记每行中存储的联系人数据类型。如需获取与内容 URI 对应的 MIME 类型,请调用 ContentResolver.getType()。

MIME 类型参考部分介绍了标准和自定义 MIME 类型的语法。

提供程序访问的替代形式

在应用开发过程中,提供程序访问的三种替代形式十分重要:

以下部分介绍了如何使用 intent 进行批量访问和修改。

批量访问

批量访问提供程序适用于以下情况:插入大量行、通过同一次方法调用将行插入到多个表中,以及在进程边界之间作为事务(称为原子操作)执行一组操作。

如需以批处理模式访问提供程序,请创建一个 ContentProviderOperation 对象数组,然后使用 ContentResolver.applyBatch() 将其分派给 content provider。您需要向此方法传递 content provider 的授权方,而不是特定的内容 URI。

这样,数组中的每个 ContentProviderOperation 对象都可以针对不同的表运行。对 ContentResolver.applyBatch() 的调用会返回一个结果数组。

ContactsContract.RawContacts 协定类的说明包含一个演示批量插入的代码段。

使用 intent 访问数据

Intent 可以提供对内容提供程序的间接访问。即使您的应用没有访问权限,您也可以让用户访问提供程序中的数据,方法是从具有权限的应用中获取结果 intent,或者激活具有权限的应用并让用户在其中工作。

通过临时权限获取访问权限

即使您没有适当的访问权限,也可以访问 content provider 中的数据,方法是向具有相应权限的应用发送 intent,并接收回包含 URI 权限的结果 intent。 这些是特定内容 URI 的权限,将持续至接收该权限的 Activity 结束。拥有永久权限的应用会在结果 Intent 中设置标记,从而授予临时权限:

注意:如果内容 URI 中包含提供程序的授权,这些标记不提供对提供程序的常规读取或写入访问权限。访问权限仅适用于 URI 本身。

向其他应用发送内容 URI 时,请至少添加其中一个标志。这些标志可为接收 intent 且以 Android 11(API 级别 30)或更高版本为目标平台的任何应用提供以下功能:

  • 根据 intent 中包含的标志,针对内容 URI 代表的数据执行读取或写入操作。
  • 获得对所含 content provider 与 URI 授权相匹配的应用的软件包可见性。发送 intent 的应用和包含 content provider 的应用可能是两个不同的应用。

提供程序在其清单中使用 <provider> 元素的 android:grantUriPermissions 属性以及 <provider> 元素的 <grant-uri-permission> 子元素为其内容 URI 定义 URI 权限。Android 中的权限指南中更详细地介绍了 URI 权限机制。

例如,即使您没有 READ_CONTACTS 权限,也可以在联系人提供程序中检索联系人的数据。在向联系人发送电子生日祝福的应用中,您可能希望执行此操作。不要请求 READ_CONTACTS(这会授予您对用户所有联系人及其所有信息的访问权限),而是让用户控制您的应用使用哪些联系人。为此,请使用以下流程:

  1. 在您的应用中,使用 startActivityForResult() 方法发送包含 ACTION_PICK 操作和“contacts”MIME 类型 CONTENT_ITEM_TYPE 的 intent。
  2. 由于此 intent 与 People 应用的“选择”activity 的 intent 过滤器匹配,因此该 activity 会进入前台。
  3. 在选择 Activity 中,用户会选择需要更新的联系人。发生此情况时,选择 Activity 会调用 setResult(resultcode, intent),以设置用于返回至应用的 Intent。该 intent 包含用户所选联系人的内容 URI 以及“extra”标志 FLAG_GRANT_READ_URI_PERMISSION。这些标记会为您的应用授予 URI 权限,以便读取内容 URI 所指向联系人的数据。然后,选择 Activity 会调用 finish(),将控制权交还给您的应用。
  4. 您的 Activity 会返回至前台,并且系统会调用此 Activity 的 onActivityResult() 方法。此方法会收到“联系人”应用中选择 Activity 所创建的结果 Intent。
  5. 通过来自结果 Intent 的内容 URI,您可以读取来自联系人提供程序的联系人数据,即使您未在清单文件中请求对该提供程序的永久读取访问权限。然后,您可以获取联系人的生日信息或邮箱,并发送电子问候。

使用其他应用

另一种让用户修改您无权访问的数据的方法是,启动一个确实具有权限的应用,让用户在该应用中执行操作。

例如,日历应用接受 ACTION_INSERT intent,该 intent 可让您激活应用的插入界面。您可以在此 intent 中传递“extra”数据,应用会使用这些数据预先填充界面。由于周期性事件的语法较为复杂,因此如需将事件插入日历提供程序,首选方法是激活拥有 ACTION_INSERT 的日历应用,然后让用户在该应用中插入事件。

使用辅助应用显示数据

如果您的应用确实具有访问权限,您可能仍会使用 intent 在其他应用中显示数据。例如,日历应用接受显示特定日期或事件的 ACTION_VIEW intent。 这样,您无需创建自己的界面即可显示日历信息。 如需详细了解此功能,请参阅日历提供程序概览。

您向其发送 intent 的应用不一定是与提供程序关联的应用。例如,您可以从联系人提供程序中检索联系人,然后向图像查看器发送 ACTION_VIEW Intent(包含用于联系人图像的内容 URI)。

合同类

协定类可定义一些常量,帮助应用使用内容 URI、列名称、Intent 操作以及内容提供程序的其他功能。提供程序不会自动包含协定类。提供程序的开发者必须定义这些内容,然后将其提供给其他开发者。Android 平台中的许多提供程序在 android.provider 软件包中均拥有对应的协定类。

例如,用户字典提供程序拥有包含内容 URI 和列名称常量的协定类 UserDictionary。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 是包含 Intent 和 Intent 数据常量的协定类。

MIME 类型参考

Content Provider 可以返回标准 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。