使用 intent 修改联系人

本课将向您展示如何使用 Intent 来插入新联系人或修改现有联系人的数据。与其直接访问联系人提供程序 (Contacts Provider),不如通过 Intent 启动联系人应用,由后者运行相应的 Activity。对于本课中描述的修改操作,如果您在 Intent 中发送了扩展数据,这些数据将被填入所启动 Activity 的界面中。

出于以下原因,使用 Intent 来插入或更新单个联系人是修改联系人提供程序的首选方式:

  • 它为您节省了开发自己的界面和代码的时间与精力。
  • 它避免了因不遵循联系人提供程序规则的修改而导致的错误。
  • 它减少了您需要申请的权限数量。您的应用无需拥有写入联系人提供程序的权限,因为它将修改操作委托给了已具备该权限的联系人应用。

使用 Intent 插入新联系人

当您的应用收到新数据时,通常需要允许用户插入新联系人。例如,餐厅评论应用可以允许用户在评论餐厅时将其添加为联系人。要通过 Intent 实现此操作,请使用您现有的数据创建 Intent,然后将其发送给联系人应用。

使用联系人应用插入联系人时,会在联系人提供程序的 ContactsContract.RawContacts 表中插入一个新的原始 (raw) 联系人。如有必要,联系人应用会提示用户选择创建原始联系人时使用的帐户类型和帐户。如果原始联系人已存在,联系人应用也会通知用户。用户随后可以选择取消插入,此时不会创建任何联系人。要了解有关原始联系人的更多信息,请参阅 联系人提供程序 API 指南。

创建 Intent

首先,创建一个带有 Intents.Insert.ACTION 操作的 Intent 对象。将 MIME 类型设置为 RawContacts.CONTENT_TYPE。例如:

Kotlin

...
// Creates a new Intent to insert a contact
val intent = Intent(ContactsContract.Intents.Insert.ACTION).apply {
    // Sets the MIME type to match the Contacts Provider
    type = ContactsContract.RawContacts.CONTENT_TYPE
}

Java

...
// Creates a new Intent to insert a contact
Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION);
// Sets the MIME type to match the Contacts Provider
intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);

如果您已经有了联系人的详细信息(例如电话号码或电子邮件地址),可以将它们作为扩展数据插入到 Intent 中。对于键值,请使用 Intents.Insert 中的相应常量。联系人应用会在其插入界面中显示这些数据,允许用户进行进一步的编辑和添加。

Kotlin

private var emailAddress: EditText? = null
private var phoneNumber: EditText? = null
...
/* Assumes EditText fields in your UI contain an email address
 * and a phone number.
 *
 */
emailAddress = findViewById(R.id.email)
phoneNumber = findViewById(R.id.phone)
...
/*
 * Inserts new data into the Intent. This data is passed to the
 * contacts app's Insert screen
 */
intent.apply {
    // Inserts an email address
    putExtra(ContactsContract.Intents.Insert.EMAIL, emailAddress?.text)
    /*
     * In this example, sets the email type to be a work email.
     * You can set other email types as necessary.
     */
    putExtra(
            ContactsContract.Intents.Insert.EMAIL_TYPE,
            ContactsContract.CommonDataKinds.Email.TYPE_WORK
    )
    // Inserts a phone number
    putExtra(ContactsContract.Intents.Insert.PHONE, phoneNumber?.text)
    /*
     * In this example, sets the phone type to be a work phone.
     * You can set other phone types as necessary.
     */
    putExtra(
            ContactsContract.Intents.Insert.PHONE_TYPE,
            ContactsContract.CommonDataKinds.Phone.TYPE_WORK
    )
}

Java

private EditText emailAddress = null;
private EditText phoneNumber = null;
...
/* Assumes EditText fields in your UI contain an email address
 * and a phone number.
 *
 */
emailAddress = (EditText) findViewById(R.id.email);
phoneNumber = (EditText) findViewById(R.id.phone);
...
/*
 * Inserts new data into the Intent. This data is passed to the
 * contacts app's Insert screen
 */
// Inserts an email address
intent.putExtra(ContactsContract.Intents.Insert.EMAIL, emailAddress.getText())
/*
 * In this example, sets the email type to be a work email.
 * You can set other email types as necessary.
 */
      .putExtra(ContactsContract.Intents.Insert.EMAIL_TYPE,
            ContactsContract.CommonDataKinds.Email.TYPE_WORK)
// Inserts a phone number
      .putExtra(ContactsContract.Intents.Insert.PHONE, phoneNumber.getText())
/*
 * In this example, sets the phone type to be a work phone.
 * You can set other phone types as necessary.
 */
      .putExtra(ContactsContract.Intents.Insert.PHONE_TYPE,
            ContactsContract.CommonDataKinds.Phone.TYPE_WORK);

创建好 Intent 后,通过调用 startActivity() 将其发送出去。

Kotlin

    /* Sends the Intent
     */
    startActivity(intent)

Java

    /* Sends the Intent
     */
    startActivity(intent);

此调用会打开联系人应用中的一个界面,允许用户输入新联系人。界面顶部会列出联系人的帐户类型和帐户名称。用户输入数据并点击完成 (Done) 后,将显示联系人应用的任务列表。用户点击返回 (Back) 即可回到您的应用。

使用 Intent 编辑现有联系人

如果用户已经选择了感兴趣的联系人,使用 Intent 编辑该联系人会很有用。例如,一个查找有邮寄地址但缺少邮政编码的联系人的应用,可以让用户选择查询邮政编码,然后将其添加到该联系人信息中。

要使用 Intent 编辑现有联系人,请遵循类似于插入联系人的步骤。按照使用 Intent 插入新联系人一节中的描述创建 Intent,但在 Intent 中添加联系人的 Contacts.CONTENT_LOOKUP_URI 和 MIME 类型 Contacts.CONTENT_ITEM_TYPE。如果您想使用已有的详细信息来编辑联系人,可以将它们放入 Intent 的扩展数据中。请注意,有些名称列无法通过 Intent 进行编辑;这些列在 ContactsContract.Contacts 类的 API 参考摘要部分的“更新 (Update)”标题下有列出。

最后,发送 Intent。作为响应,联系人应用将显示一个编辑界面。当用户完成编辑并保存后,联系人应用会显示联系人列表。当用户点击返回 (Back) 时,您的应用将会显示。

创建 Intent

要编辑联系人,请调用 Intent(action) 创建一个带有 ACTION_EDIT 操作的 Intent。调用 setDataAndType() 将 Intent 的数据值设置为联系人的 Contacts.CONTENT_LOOKUP_URI,并将 MIME 类型设置为 Contacts.CONTENT_ITEM_TYPE;因为调用 setType() 会覆盖 Intent 当前的数据值,所以您必须同时设置数据和 MIME 类型。

要获取联系人的 Contacts.CONTENT_LOOKUP_URI,请调用 Contacts.getLookupUri(id, lookupkey),并将联系人的 Contacts._IDContacts.LOOKUP_KEY 值作为参数传入。

注意:联系人的 LOOKUP_KEY 值是您应该用来检索联系人的标识符。即使提供程序更改了联系人的行 ID 以处理内部操作,它也保持不变。

以下代码片段展示了如何创建 Intent:

Kotlin

    // The Cursor that contains the Contact row
    var mCursor: Cursor? = null
    // The index of the lookup key column in the cursor
    var lookupKeyIndex: Int = 0
    // The index of the contact's _ID value
    var idIndex: Int = 0
    // The lookup key from the Cursor
    var currentLookupKey: String? = null
    // The _ID value from the Cursor
    var currentId: Long = 0
    // A content URI pointing to the contact
    var selectedContactUri: Uri? = null
    ...
    /*
     * Once the user has selected a contact to edit,
     * this gets the contact's lookup key and _ID values from the
     * cursor and creates the necessary URI.
     */
    mCursor?.apply {
        // Gets the lookup key column index
        lookupKeyIndex = getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)
        // Gets the lookup key value
        currentLookupKey = getString(lookupKeyIndex)
        // Gets the _ID column index
        idIndex = getColumnIndex(ContactsContract.Contacts._ID)
        currentId = getLong(idIndex)
        selectedContactUri = ContactsContract.Contacts.getLookupUri(currentId, mCurrentLookupKey)
    }

    // Creates a new Intent to edit a contact
    val editIntent = Intent(Intent.ACTION_EDIT).apply {
        /*
         * Sets the contact URI to edit, and the data type that the
         * Intent must match
         */
        setDataAndType(selectedContactUri, ContactsContract.Contacts.CONTENT_ITEM_TYPE)
    }

Java

    // The Cursor that contains the Contact row
    public Cursor mCursor;
    // The index of the lookup key column in the cursor
    public int lookupKeyIndex;
    // The index of the contact's _ID value
    public int idIndex;
    // The lookup key from the Cursor
    public String currentLookupKey;
    // The _ID value from the Cursor
    public long currentId;
    // A content URI pointing to the contact
    Uri selectedContactUri;
    ...
    /*
     * Once the user has selected a contact to edit,
     * this gets the contact's lookup key and _ID values from the
     * cursor and creates the necessary URI.
     */
    // Gets the lookup key column index
    lookupKeyIndex = mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY);
    // Gets the lookup key value
    currentLookupKey = mCursor.getString(lookupKeyIndex);
    // Gets the _ID column index
    idIndex = mCursor.getColumnIndex(ContactsContract.Contacts._ID);
    currentId = mCursor.getLong(idIndex);
    selectedContactUri =
            Contacts.getLookupUri(currentId, mCurrentLookupKey);
    ...
    // Creates a new Intent to edit a contact
    Intent editIntent = new Intent(Intent.ACTION_EDIT);
    /*
     * Sets the contact URI to edit, and the data type that the
     * Intent must match
     */
    editIntent.setDataAndType(selectedContactUri, ContactsContract.Contacts.CONTENT_ITEM_TYPE);

添加导航标志

在 Android 4.0(API 14 级)及更高版本中,联系人应用中的一个问题会导致导航错误。当您的应用向联系人应用发送编辑 Intent,且用户编辑并保存联系人后,点击返回 (Back) 时,他们会看到联系人列表界面。要导航回您的应用,他们必须点击最近任务 (Recents) 并选择您的应用。

为了在 Android 4.0.3(API 15 级)及更高版本中解决此问题,请向 Intent 添加扩展数据键 finishActivityOnSaveCompleted,并将其值设为 true。Android 4.0 之前的版本会接收此键,但不会产生任何影响。要设置此扩展数据,请执行以下操作:

Kotlin

    // Sets the special extended data for navigation
    editIntent.putExtra("finishActivityOnSaveCompleted", true)

Java

    // Sets the special extended data for navigation
    editIntent.putExtra("finishActivityOnSaveCompleted", true);

添加其他扩展数据

要向 Intent 添加其他扩展数据,请根据需要调用 putExtra()。您可以使用 Intents.Insert 中指定的键值来为常见的联系人字段添加扩展数据。请记住,ContactsContract.Contacts 表中的某些列无法修改。这些列在 ContactsContract.Contacts 类的 API 参考摘要部分的“更新 (Update)”标题下有列出。

发送 Intent

最后,发送您构建好的 Intent。例如:

Kotlin

    // Sends the Intent
    startActivity(editIntent)

Java

    // Sends the Intent
    startActivity(editIntent);

让用户选择使用 Intent 插入或编辑

您可以通过发送操作为 ACTION_INSERT_OR_EDITIntent,让用户选择是插入新联系人还是编辑现有联系人。例如,电子邮件客户端应用可以允许用户将收到的电子邮件地址添加到新联系人中,或将其作为现有联系人的附加地址。将此 Intent 的 MIME 类型设置为 Contacts.CONTENT_ITEM_TYPE,但不要设置数据 URI。

当您发送此 Intent 时,联系人应用会显示联系人列表。用户既可以插入新联系人,也可以选择现有联系人进行编辑。您添加到 Intent 中的任何扩展数据字段都会填充到随后出现的界面中。您可以使用 Intents.Insert 中指定的任何键值。以下代码片段展示了如何构建和发送该 Intent:

Kotlin

    // Creates a new Intent to insert or edit a contact
    val intentInsertEdit = Intent(Intent.ACTION_INSERT_OR_EDIT).apply {
        // Sets the MIME type
        type = ContactsContract.Contacts.CONTENT_ITEM_TYPE
    }
    // Add code here to insert extended data, if desired

    // Sends the Intent with an request ID
    startActivity(intentInsertEdit)

Java

    // Creates a new Intent to insert or edit a contact
    Intent intentInsertEdit = new Intent(Intent.ACTION_INSERT_OR_EDIT);
    // Sets the MIME type
    intentInsertEdit.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
    // Add code here to insert extended data, if desired
    ...
    // Sends the Intent with an request ID
    startActivity(intentInsertEdit);