インテントを使用して連絡先を編集する

このレッスンでは、Intent を使用して新しい連絡先を挿入する方法や、連絡先のデータを変更する方法について説明します。Intent は、連絡先プロバイダに直接アクセスする代わりに連絡先アプリを起動し、適切な Activity を実行します。このレッスンで説明する変更アクションでは、Intent で拡張データを送信すると、開始される Activity の UI に入力されます。

連絡先プロバイダを変更するには、Intent を使用して単一の連絡先を挿入または更新することをおすすめします。理由は以下のとおりです。

  • 独自の UI とコードを開発する時間と労力を節約できます。
  • これにより、連絡先プロバイダのルールに従わない変更によって引き起こされるエラーを回避できます。
  • リクエストする必要のある権限の数が減る。連絡先プロバイダへの書き込み権限は必要ありません。このアプリは、すでにこの権限を持っている連絡先アプリに変更を委任するためです。

インテントを使用して新しい連絡先を挿入する

アプリが新しいデータを受信したときに、ユーザーが新しい連絡先を挿入できるようにしたい場合があります。たとえば、レストランのレビューアプリでは、ユーザーがレストランをレビューするときに連絡先として追加できます。インテントを使用してこれを行うには、可能な限り多くのデータを使用してインテントを作成し、そのインテントを連絡帳アプリに送信します。

連絡先アプリを使用して連絡先を挿入すると、新しい未加工の連絡先が連絡先プロバイダの ContactsContract.RawContacts テーブルに挿入されます。必要に応じて、連絡先アプリは、未加工の連絡先の作成時に使用する口座種別と口座種別をユーザーに求めます。連絡先アプリは、未加工の連絡先がすでに存在する場合もユーザーに通知します。ユーザーは挿入をキャンセルすることもできます。キャンセルした場合は連絡先は作成されません。未加工の連絡先の詳細については、Contacts Provider API ガイドをご覧ください。

インテントを作成する

まず、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);

電話番号やメールアドレスなど、連絡先の詳細情報がすでにある場合は、それらを拡張データとしてインテントに挿入できます。Key-Value には 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);

この呼び出しによって、ユーザーが新しい連絡先を入力できる連絡先アプリの画面が開きます。連絡先のアカウントの種類と名前が画面の上部に表示されます。ユーザーがデータを入力して [完了] をクリックすると、連絡先アプリの連絡先リストが表示されます。ユーザーは [戻る] をクリックすることでアプリに戻ります。

インテントを使用して既存の連絡先を編集する

Intent を使用して既存の連絡先を編集すると、ユーザーがすでに関心のある連絡先を選択している場合は便利です。たとえば、住所は知っているが郵便番号がない連絡先を検索するアプリは、ユーザーがコードを検索して連絡先に追加するオプションを提供します。

インテントを使用して既存の連絡先を編集するには、連絡先の挿入と同様の手順を使用します。インテントを使用して新しい連絡先を挿入するセクションの説明に沿ってインテントを作成しますが、連絡先の Contacts.CONTENT_LOOKUP_URI と MIME タイプ Contacts.CONTENT_ITEM_TYPE をインテントに追加します。すでにある詳細情報を含む連絡先を編集する場合は、それらをインテントの拡張データに挿入できます。なお、一部の名前列は、インテントを使用して編集できません。これらの列は、ContactsContract.Contacts クラスの API リファレンスの summary セクションにある「Update」という見出しの下に記載されています。

最後に、インテントを送信します。レスポンスとして、連絡先アプリが編集画面を表示します。ユーザーが編集を終了して編集内容を保存すると、連絡先アプリによって連絡先リストが表示されます。ユーザーが [戻る] をクリックすると、アプリが表示されます。

インテントを作成する

連絡先を編集するには、Intent(action) を呼び出して、アクション ACTION_EDIT を含むインテントを作成します。setDataAndType() を呼び出してインテントのデータ値を連絡先の Contacts.CONTENT_LOOKUP_URI に、MIME タイプを Contacts.CONTENT_ITEM_TYPE MIME タイプに設定します。setType() を呼び出すと Intent の現在のデータ値が上書きされるため、データと MIME タイプを同時に設定する必要があります。

連絡先の Contacts.CONTENT_LOOKUP_URI を取得するには、連絡先の Contacts._ID 値と Contacts.LOOKUP_KEY 値を引数として Contacts.getLookupUri(id, lookupkey) を呼び出します。

注: 連絡先の LOOKUP_KEY 値は、連絡先の取得に使用する識別子です。プロバイダが内部操作を処理するために連絡先の行 ID を変更しても、この値は一定になります。

次のスニペットは、インテントの作成方法を示しています。

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)以降では、連絡帳アプリの問題が原因で、ナビゲーションが正しく行われません。アプリが連絡先アプリに編集インテントを送信し、ユーザーが連絡先を編集して保存すると、[戻る] をクリックすると、連絡先リストの画面が表示されます。自分のアプリに戻るには、[最近] をクリックしてアプリを選択する必要があります。

Android 4.0.3(API バージョン 15)以降でこの問題を回避するには、拡張データキー finishActivityOnSaveCompleted をインテントに追加します。値 true を指定します。Android 4.0 より前の Android バージョンもこのキーを受け入れますが、効果はありません。拡張データを設定する手順は次のとおりです。

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 で指定された Key-Value を使用して、一般的な連絡先フィールドの拡張データを追加できます。ContactsContract.Contacts テーブルには変更できない列もあります。これらの列は、ContactsContract.Contacts クラスの API リファレンスの概要セクションの「更新」に記載されています。

インテントを送信する

最後に、作成したインテントを送信します。次に例を示します。

Kotlin

    // Sends the Intent
    startActivity(editIntent)

Java

    // Sends the Intent
    startActivity(editIntent);

インテントを使用して、挿入と編集のいずれを行うのかユーザーが選択できるようにする

アクション ACTION_INSERT_OR_EDIT を使用して Intent を送信することで、連絡先を挿入するか既存の連絡先を編集するかをユーザーが選択できるようにすることができます。たとえば、メール クライアント アプリでは、ユーザーが受信メールアドレスを新しい連絡先に追加したり、既存の連絡先の追加アドレスとして追加したりできます。このインテントの MIME タイプは Contacts.CONTENT_ITEM_TYPE に設定しますが、データ URI は設定しません。

このインテントを送信すると、連絡先アプリに連絡先のリストが表示されます。ユーザーは、新しい連絡先を挿入するか、既存の連絡先を選択して編集できます。 インテントに追加した拡張データ フィールドが、表示される画面に示されます。Intents.Insert で指定された任意のキー値を使用できます。次のコード スニペットは、インテントを作成して送信する方法を示しています。

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