Поставщик контактов — это мощный и гибкий компонент Android, который управляет центральным хранилищем данных о людях на устройстве. Поставщик контактов — это источник данных, которые вы видите в приложении «Контакты» устройства, и вы также можете получить доступ к его данным в своем приложении и передавать данные между устройством и онлайн-сервисами. Поставщик работает с широким спектром источников данных и стремится управлять как можно большим объемом данных для каждого человека, что обуславливает сложность его организации. В связи с этим API поставщика включает в себя обширный набор классов контрактов и интерфейсов, упрощающих как извлечение, так и изменение данных.
В этом руководстве описывается следующее:
- Базовая структура провайдера.
- Как получить данные от провайдера.
- Как изменить данные в провайдере.
- Как написать адаптер синхронизации для синхронизации данных с вашего сервера с поставщиком контактов.
Это руководство предполагает, что вы знакомы с основами работы с поставщиками контента для Android. Чтобы узнать больше о поставщиках контента для Android, ознакомьтесь с руководством «Основы работы с поставщиками контента» .
Контакты организации-поставщика
Contacts Provider — это компонент поставщика контента Android. Он поддерживает три типа данных о человеке, каждый из которых соответствует таблице, предлагаемой поставщиком, как показано на рисунке 1:

Рисунок 1. Структура таблицы поставщика контактов.
Эти три таблицы обычно называются по именам их контрактных классов. Классы определяют константы для URI контента, имена столбцов и значения столбцов, используемые таблицами:
- Таблица
ContactsContract.Contacts - Строки, представляющие разных людей, на основе агрегации необработанных строк контактов.
- Таблица
ContactsContract.RawContacts - Строки, содержащие сводку данных о человеке, относящихся к учетной записи и типу пользователя.
- Таблица «
ContactsContract.Data - Строки, содержащие данные необработанных контактов, такие как адреса электронной почты или номера телефонов.
Другие таблицы, представленные классами контрактов в ContactsContract являются вспомогательными таблицами, которые поставщик контактов использует для управления своими операциями или поддержки определенных функций в контактах устройства или приложениях телефонии.
Необработанные контакты
Необработанный контакт представляет собой данные человека, полученные из учётной записи одного типа и имени. Поскольку поставщик контактов допускает использование нескольких онлайн-сервисов в качестве источника данных о человеке, он допускает несколько необработанных контактов для одного и того же человека. Наличие нескольких необработанных контактов также позволяет пользователю объединять данные человека из нескольких учётных записей одного типа.
Большая часть данных необработанного контакта хранится не в таблице ContactsContract.RawContacts , а в одной или нескольких строках таблицы ContactsContract.Data . Каждая строка данных содержит столбец Data.RAW_CONTACT_ID , содержащий значение RawContacts._ID родительской строки ContactsContract.RawContacts .
Важные столбцы необработанных контактов
Важные столбцы в таблице ContactsContract.RawContacts перечислены в таблице 1. Пожалуйста, прочтите примечания, следующие за таблицей:
Таблица 1. Важные столбцы необработанных контактов.
| Имя столбца | Использовать | Примечания |
|---|---|---|
ACCOUNT_NAME | Имя учётной записи для типа учётной записи, являющегося источником этого необработанного контакта. Например, имя учётной записи Google — это один из адресов Gmail владельца устройства. Подробнее см. в следующей записи для ACCOUNT_TYPE . | Формат этого имени зависит от типа учётной записи. Оно не обязательно является адресом электронной почты. |
ACCOUNT_TYPE | Тип учётной записи, являющейся источником этого необработанного контакта. Например, тип учётной записи Google — com.google . Всегда указывайте в качестве типа учётной записи идентификатор домена, которым вы владеете или управляете. Это обеспечит уникальность типа вашей учётной записи. | Тип учетной записи, предлагающий данные о контактах, обычно имеет связанный с ним адаптер синхронизации, который синхронизируется с поставщиком контактов. |
DELETED | Флаг «удалено» для необработанного контакта. | Этот флаг позволяет поставщику контактов поддерживать строку внутренне до тех пор, пока адаптеры синхронизации не смогут удалить строку со своих серверов, а затем окончательно удалить строку из репозитория. |
Примечания
Ниже приведены важные замечания о таблице ContactsContract.RawContacts :
- Имя необработанного контакта хранится не в строке таблицы
ContactsContract.RawContacts, а в строке типаContactsContract.CommonDataKinds.StructuredNameтаблицыContactsContract.Data. Необработанный контакт имеет только одну строку этого типа в таблицеContactsContract.Data. - Внимание: Чтобы использовать данные вашей учётной записи в строке необработанного контакта, её необходимо сначала зарегистрировать в
AccountManager. Для этого предложите пользователям добавить тип учётной записи и её имя в список учётных записей. В противном случае поставщик контактов автоматически удалит вашу строку необработанного контакта.Например, если вы хотите, чтобы ваше приложение поддерживало данные о контактах для вашего веб-сервиса с доменом
com.example.dataservice, а учётная запись пользователя для вашего сервиса —becky.sharp@dataservice.example.com, пользователь должен сначала добавить «тип» учётной записи (com.example.dataservice) и «имя» учётной записи (becky.smart@dataservice.example.com), прежде чем ваше приложение сможет добавлять строки необработанных контактов. Вы можете объяснить это требование пользователю в документации или предложить ему добавить тип и имя, или и то, и другое. Типы и имена учётных записей более подробно описаны в следующем разделе.
Источники необработанных данных о контактах
Чтобы понять, как работают необработанные контакты, рассмотрим пользователя «Эмили Дикинсон», на устройстве которой определены следующие три учетные записи:
-
emily.dickinson@gmail.com -
emilyd@gmail.com - Аккаунт в Twitter "belle_of_amherst"
Этот пользователь включил синхронизацию контактов для всех трех учетных записей в настройках учетных записей .
Предположим, Эмили Дикинсон открывает окно браузера, входит в Gmail как emily.dickinson@gmail.com , открывает Контакты и добавляет «Томаса Хиггинсона». Позже она входит в Gmail как emilyd@gmail.com и отправляет электронное письмо «Томасу Хиггинсону», что автоматически добавляет его в контакты. Она также подписана на «colonel_tom» (идентификатор Томаса Хиггинсона в Twitter).
В результате этой работы поставщик контактов создает три необработанных контакта:
- Необработанный контакт для «Томаса Хиггинсона», связанный с
emily.dickinson@gmail.com. Тип учётной записи — Google. - Второй необработанный контакт для «Томаса Хиггинсона», связанный с
emilyd@gmail.com. Тип учётной записи пользователя также Google. Имеется второй необработанный контакт, хотя имя совпадает с предыдущим, поскольку человек был добавлен для другой учётной записи. - Третий необработанный контакт для «Томаса Хиггинсона», связанный с «belle_of_amherst». Тип учётной записи — Twitter.
Данные
Как отмечалось ранее, данные необработанного контакта хранятся в строке ContactsContract.Data , связанной со значением _ID необработанного контакта. Это позволяет одному необработанному контакту иметь несколько экземпляров данных одного типа, таких как адреса электронной почты или номера телефонов. Например, если у «Томаса Хиггинсона» для emilyd@gmail.com (строка необработанного контакта для Томаса Хиггинсона, связанная с учётной записью Google emilyd@gmail.com ) домашний адрес электронной почты thigg@gmail.com и рабочий адрес электронной почты thomas.higginson@gmail.com , поставщик контактов сохранит обе строки адресов электронной почты и свяжет их обе с необработанным контактом.
Обратите внимание, что в этой таблице хранятся разные типы данных. Строки с отображаемым именем, номером телефона, адресом электронной почты, почтовым адресом, фотографией и информацией о веб-сайте находятся в таблице ContactsContract.Data . Для этого таблица ContactsContract.Data содержит столбцы с описательными названиями и столбцы с общими названиями. Содержимое столбца с описательным названием имеет одинаковое значение независимо от типа данных в строке, в то время как содержимое столбца с общим названием имеет разное значение в зависимости от типа данных.
Описательные названия столбцов
Вот некоторые примеры описательных названий столбцов:
-
RAW_CONTACT_ID - Значение столбца
_IDнеобработанного контакта для этих данных. -
MIMETYPE - Тип данных, хранящихся в этой строке, выраженный в виде пользовательского MIME-типа. Поставщик контактов использует MIME-типы, определенные в подклассах
ContactsContract.CommonDataKinds. Эти MIME-типы имеют открытый исходный код и могут использоваться любым приложением или адаптером синхронизации, работающим с поставщиком контактов. -
IS_PRIMARY - Если строка данных такого типа может встречаться для необработанного контакта более одного раза, столбец
IS_PRIMARYпомечает строку данных, содержащую первичные данные для этого типа. Например, если пользователь нажимает и удерживает номер телефона контакта и выбирает «Установить значение по умолчанию» , то в строкеContactsContract.Data, содержащей этот номер, столбецIS_PRIMARYбудет установлен в ненулевое значение.
Общие имена столбцов
Существует 15 общих столбцов с именами DATA1 DATA15 , которые доступны всем, и ещё четыре общих столбца с SYNC1 – SYNC4 , которые должны использоваться только адаптерами синхронизации. Константы общих имён столбцов работают всегда, независимо от типа данных, содержащихся в строке.
Столбец DATA1 индексирован. Поставщик контактов всегда использует этот столбец для данных, которые, по его мнению, будут наиболее часто встречающимися в запросах. Например, в строке адреса электронной почты этот столбец содержит фактический адрес электронной почты.
По соглашению столбец DATA15 зарезервирован для хранения данных больших двоичных объектов (BLOB), таких как миниатюры фотографий.
Имена столбцов, специфичные для типа
Для упрощения работы со столбцами для строк определённого типа поставщик контактов также предоставляет константы имён столбцов, специфичные для конкретного типа, определённые в подклассах ContactsContract.CommonDataKinds . Эти константы просто присваивают одному и тому же столбцу другое имя, что упрощает доступ к данным в строке определённого типа.
Например, класс ContactsContract.CommonDataKinds.Email определяет константы имён столбцов, специфичные для конкретного типа, для строки ContactsContract.Data с MIME-типом Email.CONTENT_ITEM_TYPE . Класс содержит константу ADDRESS для столбца адреса электронной почты. Фактическое значение ADDRESS — «data1», что совпадает с общим именем столбца.
Внимание: не добавляйте собственные данные в таблицу ContactsContract.Data , используя строку с одним из предопределенных MIME-типов поставщика. Это может привести к потере данных или сбоям в работе поставщика. Например, не следует добавлять строку с MIME-типом Email.CONTENT_ITEM_TYPE , содержащую имя пользователя вместо адреса электронной почты в столбце DATA1 . Если вы используете собственный MIME-тип для строки, вы можете задать собственные имена столбцов, соответствующие типу, и использовать столбцы по своему усмотрению.
На рисунке 2 показано, как описательные столбцы и столбцы данных отображаются в строке ContactsContract.Data , а также как имена столбцов, специфичные для конкретного типа, «накладываются» на общие имена столбцов.

Рисунок 2. Имена столбцов, специфичные для типа, и общие имена столбцов.
Классы имен столбцов, специфичные для определенного типа
В таблице 2 перечислены наиболее часто используемые классы имен столбцов, зависящие от типа:
Таблица 2. Классы имен столбцов, специфичные для определенного типа
| Класс отображения | Тип данных | Примечания |
|---|---|---|
ContactsContract.CommonDataKinds.StructuredName | Данные имени для необработанного контакта, связанного с этой строкой данных. | Необработанный контакт имеет только одну из этих строк. |
ContactsContract.CommonDataKinds.Photo | Основная фотография необработанного контакта, связанного с этой строкой данных. | Необработанный контакт имеет только одну из этих строк. |
ContactsContract.CommonDataKinds.Email | Адрес электронной почты необработанного контакта, связанного с этой строкой данных. | У необработанного контакта может быть несколько адресов электронной почты. |
ContactsContract.CommonDataKinds.StructuredPostal | Почтовый адрес необработанного контакта, связанного с этой строкой данных. | Необработанный контакт может иметь несколько почтовых адресов. |
ContactsContract.CommonDataKinds.GroupMembership | Идентификатор, который связывает необработанный контакт с одной из групп в поставщике контактов. | Группы — это необязательный параметр, определяемый типом и именем учётной записи. Более подробно они описаны в разделе Группы контактов . |
Контакты
Поставщик контактов объединяет необработанные строки контактов по всем типам и именам учётных записей, формируя контакт . Это упрощает отображение и изменение всех данных, собранных пользователем для конкретного человека. Поставщик контактов управляет созданием новых строк контактов и агрегацией необработанных контактов с существующей строкой контактов. Ни приложения, ни адаптеры синхронизации не могут добавлять контакты, а некоторые столбцы в строке контактов доступны только для чтения.
Примечание: при попытке добавить контакт в поставщик контактов с помощью метода insert() возникнет исключение UnsupportedOperationException . При попытке обновить столбец, доступный только для чтения, обновление будет проигнорировано.
Поставщик контактов создаёт новый контакт в ответ на добавление нового необработанного контакта, который не соответствует ни одному из существующих контактов. Поставщик также делает это, если данные существующего необработанного контакта изменяются таким образом, что он перестаёт соответствовать контакту, к которому он был ранее прикреплён. Если приложение или адаптер синхронизации создаёт новый необработанный контакт, соответствующий существующему контакту, новый необработанный контакт агрегируется с существующим контактом.
Поставщик контактов связывает строку контакта со строками необработанных контактов с помощью столбца _ID строки контакта в таблице Contacts . Столбец CONTACT_ID таблицы необработанных контактов ContactsContract.RawContacts содержит значения _ID для строки контакта, связанной с каждой строкой необработанных контактов.
Таблица ContactsContract.Contacts также содержит столбец LOOKUP_KEY , который представляет собой «постоянную» ссылку на строку контакта. Поскольку поставщик контактов автоматически поддерживает контакты, он может изменить значение _ID строки контакта в ответ на агрегацию или синхронизацию. Даже в этом случае URI контента CONTENT_LOOKUP_URI в сочетании с LOOKUP_KEY контакта по-прежнему будет указывать на строку контакта, поэтому вы можете использовать LOOKUP_KEY для управления ссылками на «избранные» контакты и т. д. Этот столбец имеет собственный формат, не связанный с форматом столбца _ID .
На рисунке 3 показано, как три основные таблицы соотносятся друг с другом.

Рисунок 3. Связи таблиц «Контакты», «Необработанные контакты» и «Подробности».
Внимание: если вы публикуете свое приложение в магазине Google Play или если ваше приложение работает на устройстве под управлением Android 10 (уровень API 29) или выше, имейте в виду, что ограниченный набор полей и методов данных контактов устарели.
При указанных условиях система периодически очищает любые значения, записанные в следующие поля данных:
-
ContactsContract.ContactOptionsColumns.LAST_TIME_CONTACTED -
ContactsContract.ContactOptionsColumns.TIMES_CONTACTED -
ContactsContract.DataUsageStatColumns.LAST_TIME_USED -
ContactsContract.DataUsageStatColumns.TIMES_USED
API, используемые для настройки вышеуказанных полей данных, также устарели:
Кроме того, следующие поля больше не возвращают частые контакты. Обратите внимание, что некоторые из этих полей влияют на рейтинг контактов только в том случае, если контакты относятся к определённому типу данных .
-
ContactsContract.Contacts.CONTENT_FREQUENT_URI -
ContactsContract.Contacts.CONTENT_STREQUENT_URI -
ContactsContract.Contacts.CONTENT_STREQUENT_FILTER_URI -
CONTENT_FILTER_URI(влияет только на типы данных Email , Phone , Callable и Contactables ) -
ENTERPRISE_CONTENT_FILTER_URI(влияет только на типы данных Email , Phone и Callable )
Если ваши приложения обращаются к этим полям или API или обновляют их, используйте альтернативные методы. Например, вы можете реализовать определённые сценарии, используя поставщиков частного контента или другие данные, хранящиеся в вашем приложении или внутренних системах.
Чтобы убедиться, что это изменение не повлияет на функциональность вашего приложения, вы можете вручную очистить эти поля данных. Для этого выполните следующую команду ADB на устройстве под управлением Android 4.1 (API уровня 16) или выше:
adb shell content delete \ --uri content://com.android.contacts/contacts/delete_usage
Данные от адаптеров синхронизации
Пользователи вводят данные о контактах непосредственно в устройство, но данные также поступают в поставщик контактов из веб-сервисов через адаптеры синхронизации , которые автоматизируют передачу данных между устройством и сервисами. Адаптеры синхронизации работают в фоновом режиме под управлением системы и вызывают методы ContentResolver для управления данными.
В Android веб-служба, с которой работает адаптер синхронизации, определяется типом учётной записи. Каждый адаптер синхронизации работает с одним типом учётной записи, но может поддерживать несколько имён для этого типа. Типы и имена учётных записей кратко описаны в разделе « Источники необработанных данных о контактах» . Следующие определения содержат более подробную информацию и описывают, как тип и имя учётной записи связаны с адаптерами синхронизации и службами.
- Тип счета
- Идентифицирует службу, в которой пользователь сохранил данные. В большинстве случаев пользователю необходимо пройти аутентификацию в службе. Например, Google Контакты — это тип учётной записи, идентифицируемый кодом
google.com. Это значение соответствует типу учётной записи, используемомуAccountManager. - Имя учетной записи
- Определяет конкретную учётную запись или имя пользователя для типа учётной записи. Учётные записи Google Контакты аналогичны учётным записям Google, в которых в качестве имени используется адрес электронной почты. Другие сервисы могут использовать имя пользователя, состоящее из одного слова, или числовой идентификатор.
Типы учётных записей не обязательно должны быть уникальными. Пользователь может настроить несколько учётных записей Google Контактов и загрузить их данные в Поставщик контактов. Это может произойти, если у пользователя есть один набор личных контактов для имени личного аккаунта и другой набор для рабочего. Имена учётных записей обычно уникальны. Вместе они определяют конкретный поток данных между Поставщиком контактов и внешней службой.
Если вы хотите перенести данные вашего сервиса в Contacts Provider, вам необходимо написать собственный адаптер синхронизации. Подробнее об этом см. в разделе Адаптеры синхронизации Contacts Provider .
На рисунке 4 показано, как поставщик контактов вписывается в поток данных о людях. В поле «Адаптеры синхронизации» каждый адаптер отмечен типом своей учётной записи.

Рисунок 4. Поток данных поставщика контактов.
Требуемые разрешения
Приложения, желающие получить доступ к поставщику контактов, должны запросить следующие разрешения:
- Доступ для чтения к одной или нескольким таблицам
-
READ_CONTACTS, указанный вAndroidManifest.xmlс элементом<uses-permission>как<uses-permission android:name="android.permission.READ_CONTACTS">. - Доступ для записи к одной или нескольким таблицам
-
WRITE_CONTACTS, указанный вAndroidManifest.xmlс элементом<uses-permission>как<uses-permission android:name="android.permission.WRITE_CONTACTS">.
Эти разрешения не распространяются на данные профиля пользователя. Профиль пользователя и необходимые для него разрешения обсуждаются в следующем разделе «Профиль пользователя» .
Помните, что данные контактов пользователя являются персональными и конфиденциальными. Пользователи заботятся о своей конфиденциальности, поэтому они не хотят, чтобы приложения собирали данные о них или их контактах. Если им неясно, зачем вам нужно разрешение на доступ к данным их контактов, они могут поставить вашему приложению низкую оценку или просто отказаться от его установки.
Профиль пользователя
Таблица ContactsContract.Contacts содержит одну строку с данными профиля пользователя устройства. Эти данные описывают user устройства, а не один из его контактов. Строка контактов профиля связана со строкой необработанных контактов для каждой системы, использующей профиль. Каждая строка необработанных контактов профиля может содержать несколько строк данных. Константы для доступа к профилю пользователя доступны в классе ContactsContract.Profile .
Доступ к профилю пользователя требует специальных разрешений. Помимо разрешений READ_CONTACTS и WRITE_CONTACTS необходимых для чтения и записи, для доступа к профилю пользователя требуются разрешения android.Manifest.permission#READ_PROFILE и android.Manifest.permission#WRITE_PROFILE для чтения и записи соответственно.
Помните, что профиль пользователя следует рассматривать как конфиденциальную информацию. Разрешение android.Manifest.permission#READ_PROFILE позволяет получить доступ к персональным данным пользователя устройства. Обязательно укажите пользователю, зачем вам нужны разрешения на доступ к профилю, в описании вашего приложения.
Чтобы получить строку контактов, содержащую профиль пользователя, вызовите метод ContentResolver.query() . Установите URI контента на CONTENT_URI и не указывайте критерии выбора. Вы также можете использовать этот URI контента в качестве базового URI для получения необработанных контактов или данных профиля. Например, этот фрагмент кода извлекает данные профиля:
Котлин
// Sets the columns to retrieve for the user profile projection = arrayOf( ContactsContract.Profile._ID, ContactsContract.Profile.DISPLAY_NAME_PRIMARY, ContactsContract.Profile.LOOKUP_KEY, ContactsContract.Profile.PHOTO_THUMBNAIL_URI ) // Retrieves the profile from the Contacts Provider profileCursor = contentResolver.query( ContactsContract.Profile.CONTENT_URI, projection, null, null, null )
Ява
// Sets the columns to retrieve for the user profile projection = new String[] { Profile._ID, Profile.DISPLAY_NAME_PRIMARY, Profile.LOOKUP_KEY, Profile.PHOTO_THUMBNAIL_URI }; // Retrieves the profile from the Contacts Provider profileCursor = getContentResolver().query( Profile.CONTENT_URI, projection , null, null, null);
Примечание: Если вы извлекаете несколько строк контактов и хотите определить, является ли одна из них профилем пользователя, проверьте столбец IS_USER_PROFILE этой строки. Значение этого столбца равно «1», если контакт является профилем пользователя.
Метаданные поставщика контактов
Поставщик контактов управляет данными, отслеживающими состояние данных контактов в репозитории. Эти метаданные о репозитории хранятся в различных местах, включая строки таблиц Raw Contacts, Data и Contacts, таблицы ContactsContract.Settings и ContactsContract.SyncState . В следующей таблице показано влияние каждого из этих элементов метаданных:
Таблица 3. Метаданные в поставщике контактов
| Стол | Столбец | Ценности | Значение |
|---|---|---|---|
ContactsContract.RawContacts | DIRTY | "0" - не изменилось с момента последней синхронизации. | Отмечает необработанные контакты, которые были изменены на устройстве и должны быть синхронизированы с сервером. Значение автоматически устанавливается поставщиком контактов при обновлении строки приложениями Android. Адаптеры синхронизации, изменяющие необработанные контакты или таблицы данных, всегда должны добавлять строку |
| «1» — изменено с момента последней синхронизации, необходимо синхронизировать обратно с сервером. | |||
ContactsContract.RawContacts | VERSION | Номер версии этой строки. | Поставщик контактов автоматически увеличивает это значение при каждом изменении строки или связанных с ней данных. |
ContactsContract.Data | DATA_VERSION | Номер версии этой строки. | Поставщик контактов автоматически увеличивает это значение при каждом изменении строки данных. |
ContactsContract.RawContacts | SOURCE_ID | Строковое значение, однозначно идентифицирующее этот необработанный контакт в учетной записи, в которой он был создан. | Когда адаптер синхронизации создаёт новый необработанный контакт, в этом столбце должен быть указан уникальный идентификатор сервера для этого необработанного контакта. Когда приложение Android создаёт новый необработанный контакт, оно должно оставить этот столбец пустым. Это даёт адаптеру синхронизации сигнал о необходимости создать новый необработанный контакт на сервере и получить значение для SOURCE_ID .В частности, идентификатор источника должен быть уникальным для каждого типа учетной записи и должен быть стабильным при синхронизациях:
|
ContactsContract.Groups | GROUP_VISIBLE | «0» — контакты в этой группе не должны отображаться в интерфейсах приложений Android. | Этот столбец предназначен для совместимости с серверами, которые позволяют пользователю скрывать контакты в определенных группах. |
| «1» — контакты в этой группе могут быть видны в интерфейсах приложений. | |||
ContactsContract.Settings | UNGROUPED_VISIBLE | «0» — для этой учетной записи и типа учетной записи контакты, не принадлежащие ни одной группе, невидимы для пользовательских интерфейсов приложений Android. | По умолчанию контакты невидимы, если ни один из их необработанных контактов не принадлежит группе (принадлежность к группе для необработанного контакта определяется одной или несколькими строками ContactsContract.CommonDataKinds.GroupMembership в таблице ContactsContract.Data ). Установив этот флаг в строке таблицы ContactsContract.Settings для типа учётной записи и учётной записи, можно принудительно сделать видимыми контакты без групп. Этот флаг используется, например, для отображения контактов с серверов, не использующих группы. |
| «1» — для этой учетной записи и типа учетной записи контакты, не принадлежащие ни одной группе, видны пользовательским интерфейсам приложений. | |||
ContactsContract.SyncState | (все) | Используйте эту таблицу для хранения метаданных вашего адаптера синхронизации. | С помощью этой таблицы вы можете постоянно хранить на устройстве состояние синхронизации и другие данные, связанные с синхронизацией. |
Контакты Доступ к провайдеру
В этом разделе описываются рекомендации по доступу к данным поставщика контактов с акцентом на следующее:
- Запросы сущностей.
- Пакетная модификация.
- Извлечение и изменение с намерениями.
- Целостность данных.
Внесение изменений с помощью адаптера синхронизации также более подробно описано в разделе Контакты Поставщик адаптеров синхронизации .
Запрос сущностей
Поскольку таблицы поставщика контактов организованы иерархически, часто бывает полезно извлечь строку и все связанные с ней «дочерние» строки. Например, чтобы отобразить всю информацию о человеке, может потребоваться извлечь все строки ContactsContract.RawContacts для одной строки ContactsContract.Contacts или все строки ContactsContract.CommonDataKinds.Email для одной строки ContactsContract.RawContacts . Для этого поставщик контактов предлагает конструкции сущностей , которые действуют как соединения таблиц в базе данных.
Сущность подобна таблице, состоящей из выбранных столбцов родительской и дочерней таблиц. При запросе сущности вы указываете проекцию и критерии поиска на основе доступных столбцов сущности. Результатом является Cursor , содержащий по одной строке для каждой извлеченной строки дочерней таблицы. Например, если вы запрашиваете у ContactsContract.Contacts.Entity имя контакта и все строки ContactsContract.CommonDataKinds.Email для всех необработанных контактов с этим именем, вы получите Cursor содержащий по одной строке для каждой строки ContactsContract.CommonDataKinds.Email .
Сущности упрощают запросы. Используя сущность, вы можете получить все данные о контактах или необработанных контактах одновременно, вместо того, чтобы сначала запрашивать идентификатор из родительской таблицы, а затем запрашивать этот идентификатор из дочерней таблицы. Кроме того, поставщик контактов обрабатывает запрос к сущности в рамках одной транзакции, что гарантирует внутреннюю согласованность полученных данных.
Примечание: Сущность обычно не содержит все столбцы родительской и дочерней таблиц. При попытке работы с именем столбца, которого нет в списке констант имён столбцов для сущности, возникнет Exception .
В следующем фрагменте кода показано, как получить все необработанные строки контактов для контакта. Этот фрагмент является частью более крупного приложения, состоящего из двух действий: «main» и «detail». Основное действие отображает список строк контактов; когда пользователь выбирает одно из них, действие отправляет его идентификатор в действие «detail». Действие «detail» использует ContactsContract.Contacts.Entity для отображения всех строк данных всех необработанных контактов, связанных с выбранным контактом.
Этот фрагмент взят из упражнения «detail»:
Котлин
... /* * Appends the entity path to the URI. In the case of the Contacts Provider, the * expected URI is content://com.google.contacts/#/entity (# is the ID value). */ contactUri = Uri.withAppendedPath( contactUri, ContactsContract.Contacts.Entity.CONTENT_DIRECTORY ) // Initializes the loader identified by LOADER_ID. loaderManager.initLoader( LOADER_ID, // The identifier of the loader to initialize null, // Arguments for the loader (in this case, none) this // The context of the activity ) // Creates a new cursor adapter to attach to the list view cursorAdapter = SimpleCursorAdapter( this, // the context of the activity R.layout.detail_list_item, // the view item containing the detail widgets mCursor, // the backing cursor fromColumns, // the columns in the cursor that provide the data toViews, // the views in the view item that display the data 0) // flags // Sets the ListView's backing adapter. rawContactList.adapter = cursorAdapter ... override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { /* * Sets the columns to retrieve. * RAW_CONTACT_ID is included to identify the raw contact associated with the data row. * DATA1 contains the first column in the data row (usually the most important one). * MIMETYPE indicates the type of data in the data row. */ val projection: Array<String> = arrayOf( ContactsContract.Contacts.Entity.RAW_CONTACT_ID, ContactsContract.Contacts.Entity.DATA1, ContactsContract.Contacts.Entity.MIMETYPE ) /* * Sorts the retrieved cursor by raw contact id, to keep all data rows for a single raw * contact collated together. */ val sortOrder = "${ContactsContract.Contacts.Entity.RAW_CONTACT_ID} ASC" /* * Returns a new CursorLoader. The arguments are similar to * ContentResolver.query(), except for the Context argument, which supplies the location of * the ContentResolver to use. */ return CursorLoader( applicationContext, // The activity's context contactUri, // The entity content URI for a single contact projection, // The columns to retrieve null, // Retrieve all the raw contacts and their data rows. null, // sortOrder // Sort by the raw contact ID. ) }
Ява
... /* * Appends the entity path to the URI. In the case of the Contacts Provider, the * expected URI is content://com.google.contacts/#/entity (# is the ID value). */ contactUri = Uri.withAppendedPath( contactUri, ContactsContract.Contacts.Entity.CONTENT_DIRECTORY); // Initializes the loader identified by LOADER_ID. getLoaderManager().initLoader( LOADER_ID, // The identifier of the loader to initialize null, // Arguments for the loader (in this case, none) this); // The context of the activity // Creates a new cursor adapter to attach to the list view cursorAdapter = new SimpleCursorAdapter( this, // the context of the activity R.layout.detail_list_item, // the view item containing the detail widgets mCursor, // the backing cursor fromColumns, // the columns in the cursor that provide the data toViews, // the views in the view item that display the data 0); // flags // Sets the ListView's backing adapter. rawContactList.setAdapter(cursorAdapter); ... @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { /* * Sets the columns to retrieve. * RAW_CONTACT_ID is included to identify the raw contact associated with the data row. * DATA1 contains the first column in the data row (usually the most important one). * MIMETYPE indicates the type of data in the data row. */ String[] projection = { ContactsContract.Contacts.Entity.RAW_CONTACT_ID, ContactsContract.Contacts.Entity.DATA1, ContactsContract.Contacts.Entity.MIMETYPE }; /* * Sorts the retrieved cursor by raw contact id, to keep all data rows for a single raw * contact collated together. */ String sortOrder = ContactsContract.Contacts.Entity.RAW_CONTACT_ID + " ASC"; /* * Returns a new CursorLoader. The arguments are similar to * ContentResolver.query(), except for the Context argument, which supplies the location of * the ContentResolver to use. */ return new CursorLoader( getApplicationContext(), // The activity's context contactUri, // The entity content URI for a single contact projection, // The columns to retrieve null, // Retrieve all the raw contacts and their data rows. null, // sortOrder); // Sort by the raw contact ID. }
После завершения загрузки LoaderManager вызывает обратный вызов метода onLoadFinished() . Одним из входящих аргументов этого метода является Cursor с результатами запроса. В вашем приложении вы можете получить данные из этого Cursor для отображения или дальнейшей работы с ними.
Пакетная модификация
По возможности следует добавлять, обновлять и удалять данные в поставщике контактов в «пакетном режиме», создавая ArrayList объектов ContentProviderOperation и вызывая applyBatch() . Поскольку поставщик контактов выполняет все операции в applyBatch() в одной транзакции, ваши изменения никогда не приведут к несогласованности данных в репозитории контактов. Пакетное изменение также упрощает одновременную вставку необработанного контакта и его подробных данных.
Примечание: Чтобы изменить отдельный необработанный контакт, рассмотрите возможность отправки намерения в приложение «Контакты» устройства, а не обработку изменений в самом приложении. Подробнее об этом см. в разделе «Извлечение и изменение с помощью намерений» .
Пределы текучести
Пакетное изменение, содержащее большое количество операций, может блокировать другие процессы, что в целом негативно скажется на пользовательском опыте. Чтобы организовать все необходимые изменения в минимальное количество отдельных списков и одновременно предотвратить блокировку системы, следует установить точки выхода для одной или нескольких операций. Точка выхода — это объект ContentProviderOperation , значение isYieldAllowed() которого равно true . Когда поставщик контактов достигает точки выхода, он приостанавливает свою работу, чтобы дать возможность другим процессам выполниться, и закрывает текущую транзакцию. При повторном запуске поставщик продолжает работу со следующей операцией в ArrayList и начинает новую транзакцию.
Точки выхода приводят к выполнению более одной транзакции за один вызов applyBatch() . Поэтому следует установить точку выхода для последней операции для набора связанных строк. Например, следует установить точку выхода для последней операции в наборе, которая добавляет строки необработанного контакта и связанные с ним строки данных, или для последней операции для набора строк, связанных с одним контактом.
Точки выхода также являются единицей атомарной операции. Все обращения между двумя точками выхода будут либо успешными, либо неудачными как единое целое. Если точки выхода не установлены, наименьшей атомарной операцией будет весь пакет операций. Использование точек выхода предотвращает снижение производительности системы операциями, одновременно гарантируя атомарность подмножества операций.
Модификация обратных ссылок
При вставке новой строки необработанного контакта и связанных с ней строк данных как набора объектов ContentProviderOperation необходимо связать строки данных со строкой необработанного контакта, вставив значение _ID необработанного контакта в качестве значения RAW_CONTACT_ID . Однако это значение недоступно при создании ContentProviderOperation для строки данных, поскольку вы ещё не применили ContentProviderOperation к строке необработанного контакта. Для решения этой проблемы класс ContentProviderOperation.Builder имеет метод withValueBackReference() . Этот метод позволяет вставить или изменить столбец с результатом предыдущей операции.
Метод withValueBackReference() имеет два аргумента:
-
key - Ключ пары «ключ-значение». Значением этого аргумента должно быть имя столбца в таблице, которую вы изменяете.
-
previousResult - Индекс (с нуля) значения в массиве объектов
ContentProviderResultизapplyBatch(). По мере применения пакетных операций результат каждой операции сохраняется в промежуточном массиве результатов. ЗначениеpreviousResult— это индекс одного из этих результатов, который извлекается и сохраняется вместе сkey. Это позволяет вставить новую запись необработанного контакта и получить значение его_ID, а затем создать обратную ссылку на это значение при добавлении строкиContactsContract.Data.Весь массив результатов создаётся при первом вызове
applyBatch()и имеет размер, равный размеруArrayListпредоставленных вами объектовContentProviderOperation. Однако все элементы массива результатов устанавливаются вnull, и если вы попытаетесь сделать обратную ссылку на результат операции, которая ещё не была применена,withValueBackReference()выдастException.
В следующих фрагментах показано, как вставить новый необработанный контакт и данные в пакетном режиме. Они включают код, который устанавливает точку выхода и использует обратную ссылку.
Первый фрагмент кода извлекает контактные данные из пользовательского интерфейса. На этом этапе пользователь уже выбрал учётную запись, для которой необходимо добавить новый необработанный контакт.
Котлин
// Creates a contact entry from the current UI values, using the currently-selected account. private fun createContactEntry() { /* * Gets values from the UI */ val name = contactNameEditText.text.toString() val phone = contactPhoneEditText.text.toString() val email = contactEmailEditText.text.toString() val phoneType: String = contactPhoneTypes[mContactPhoneTypeSpinner.selectedItemPosition] val emailType: String = contactEmailTypes[mContactEmailTypeSpinner.selectedItemPosition]
Ява
// Creates a contact entry from the current UI values, using the currently-selected account. protected void createContactEntry() { /* * Gets values from the UI */ String name = contactNameEditText.getText().toString(); String phone = contactPhoneEditText.getText().toString(); String email = contactEmailEditText.getText().toString(); int phoneType = contactPhoneTypes.get( contactPhoneTypeSpinner.getSelectedItemPosition()); int emailType = contactEmailTypes.get( contactEmailTypeSpinner.getSelectedItemPosition());
Следующий фрагмент создает операцию по вставке строки необработанного контакта в таблицу ContactsContract.RawContacts :
Котлин
/* * Prepares the batch operation for inserting a new raw contact and its data. Even if * the Contacts Provider does not have any data for this person, you can't add a Contact, * only a raw contact. The Contacts Provider will then add a Contact automatically. */ // Creates a new array of ContentProviderOperation objects. val ops = arrayListOf<ContentProviderOperation>() /* * Creates a new raw contact with its account type (server type) and account name * (user's account). Remember that the display name is not stored in this row, but in a * StructuredName data row. No other data is required. */ var op: ContentProviderOperation.Builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, selectedAccount.name) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, selectedAccount.type) // Builds the operation and adds it to the array of operations ops.add(op.build())
Ява
/* * Prepares the batch operation for inserting a new raw contact and its data. Even if * the Contacts Provider does not have any data for this person, you can't add a Contact, * only a raw contact. The Contacts Provider will then add a Contact automatically. */ // Creates a new array of ContentProviderOperation objects. ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); /* * Creates a new raw contact with its account type (server type) and account name * (user's account). Remember that the display name is not stored in this row, but in a * StructuredName data row. No other data is required. */ ContentProviderOperation.Builder op = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, selectedAccount.getType()) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, selectedAccount.getName()); // Builds the operation and adds it to the array of operations ops.add(op.build());
Затем код создает строки данных для отображаемого имени, телефона и адреса электронной почты.
Каждый объект конструктора операций использует withValueBackReference() для получения RAW_CONTACT_ID . Ссылка указывает на объект ContentProviderResult из первой операции, которая добавляет строку необработанного контакта и возвращает её новое значение _ID . В результате каждая строка данных автоматически связывается своим RAW_CONTACT_ID с новой строкой ContactsContract.RawContacts к которой она принадлежит.
Объект ContentProviderOperation.Builder , который добавляет строку электронной почты, помечается с помощью withYieldAllowed() , который устанавливает точку выхода:
Котлин
// Creates the display name for the new raw contact, as a StructuredName data row. op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) /* * withValueBackReference sets the value of the first argument to the value of * the ContentProviderResult indexed by the second argument. In this particular * call, the raw contact ID column of the StructuredName data row is set to the * value of the result returned by the first operation, which is the one that * actually adds the raw contact row. */ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) // Sets the data row's MIME type to StructuredName .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) // Sets the data row's display name to the name in the UI. .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name) // Builds the operation and adds it to the array of operations ops.add(op.build()) // Inserts the specified phone number and type as a Phone data row op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) /* * Sets the value of the raw contact id column to the new raw contact ID returned * by the first operation in the batch. */ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) // Sets the data row's MIME type to Phone .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) // Sets the phone number and type .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType) // Builds the operation and adds it to the array of operations ops.add(op.build()) // Inserts the specified email and type as a Phone data row op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) /* * Sets the value of the raw contact id column to the new raw contact ID returned * by the first operation in the batch. */ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) // Sets the data row's MIME type to Email .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) // Sets the email address and type .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email) .withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType) /* * Demonstrates a yield point. At the end of this insert, the batch operation's thread * will yield priority to other threads. Use after every set of operations that affect a * single contact, to avoid degrading performance. */ op.withYieldAllowed(true) // Builds the operation and adds it to the array of operations ops.add(op.build())
Ява
// Creates the display name for the new raw contact, as a StructuredName data row. op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) /* * withValueBackReference sets the value of the first argument to the value of * the ContentProviderResult indexed by the second argument. In this particular * call, the raw contact ID column of the StructuredName data row is set to the * value of the result returned by the first operation, which is the one that * actually adds the raw contact row. */ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) // Sets the data row's MIME type to StructuredName .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) // Sets the data row's display name to the name in the UI. .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name); // Builds the operation and adds it to the array of operations ops.add(op.build()); // Inserts the specified phone number and type as a Phone data row op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) /* * Sets the value of the raw contact id column to the new raw contact ID returned * by the first operation in the batch. */ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) // Sets the data row's MIME type to Phone .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) // Sets the phone number and type .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, phoneType); // Builds the operation and adds it to the array of operations ops.add(op.build()); // Inserts the specified email and type as a Phone data row op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) /* * Sets the value of the raw contact id column to the new raw contact ID returned * by the first operation in the batch. */ .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0) // Sets the data row's MIME type to Email .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) // Sets the email address and type .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email) .withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType); /* * Demonstrates a yield point. At the end of this insert, the batch operation's thread * will yield priority to other threads. Use after every set of operations that affect a * single contact, to avoid degrading performance. */ op.withYieldAllowed(true); // Builds the operation and adds it to the array of operations ops.add(op.build());
The last snippet shows the call to applyBatch() that inserts the new raw contact and data rows.
Котлин
// Ask the Contacts Provider to create a new contact Log.d(TAG, "Selected account: ${mSelectedAccount.name} (${mSelectedAccount.type})") Log.d(TAG, "Creating contact: $name") /* * Applies the array of ContentProviderOperation objects in batch. The results are * discarded. */ try { contentResolver.applyBatch(ContactsContract.AUTHORITY, ops) } catch (e: Exception) { // Display a warning val txt: String = getString(R.string.contactCreationFailure) Toast.makeText(applicationContext, txt, Toast.LENGTH_SHORT).show() // Log exception Log.e(TAG, "Exception encountered while inserting contact: $e") } }
Ява
// Ask the Contacts Provider to create a new contact Log.d(TAG,"Selected account: " + selectedAccount.getName() + " (" + selectedAccount.getType() + ")"); Log.d(TAG,"Creating contact: " + name); /* * Applies the array of ContentProviderOperation objects in batch. The results are * discarded. */ try { getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); } catch (Exception e) { // Display a warning Context ctx = getApplicationContext(); CharSequence txt = getString(R.string.contactCreationFailure); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(ctx, txt, duration); toast.show(); // Log exception Log.e(TAG, "Exception encountered while inserting contact: " + e); } }
Batch operations also allow you to implement optimistic concurrency control , a method of applying modification transactions without having to lock the underlying repository. To use this method, you apply the transaction and then check for other modifications that may have been made at the same time. If you find an inconsistent modification has occurred, you roll back your transaction and retry it.
Optimistic concurrency control is useful for a mobile device, where there's only one user at a time, and simultaneous accesses to a data repository are rare. Because locking isn't used, no time is wasted on setting locks or waiting for other transactions to release their locks.
To use optimistic concurrency control while updating a single ContactsContract.RawContacts row, follow these steps:
- Retrieve the raw contact's
VERSIONcolumn along with the other data you retrieve. - Create a
ContentProviderOperation.Builderobject suitable for enforcing a constraint, using the methodnewAssertQuery(Uri). For the content URI, useRawContacts.CONTENT_URIwith the raw contact's_IDappended to it. - For the
ContentProviderOperation.Builderobject, callwithValue()to compare theVERSIONcolumn to the version number you just retrieved. - For the same
ContentProviderOperation.Builder, callwithExpectedCount()to ensure that only one row is tested by this assertion. - Call
build()to create theContentProviderOperationobject, then add this object as the first object in theArrayListthat you pass toapplyBatch(). - Apply the batch transaction.
If the raw contact row is updated by another operation between the time you read the row and the time you attempt to modify it, the "assert" ContentProviderOperation will fail, and the entire batch of operations will be backed out. You can then choose to retry the batch or take some other action.
The following snippet demonstrates how to create an "assert" ContentProviderOperation after querying for a single raw contact using a CursorLoader :
Котлин
/* * The application uses CursorLoader to query the raw contacts table. The system calls this method * when the load is finished. */ override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor) { // Gets the raw contact's _ID and VERSION values rawContactID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)) mVersion = cursor.getInt(cursor.getColumnIndex(SyncColumns.VERSION)) } ... // Sets up a Uri for the assert operation val rawContactUri: Uri = ContentUris.withAppendedId( ContactsContract.RawContacts.CONTENT_URI, rawContactID ) // Creates a builder for the assert operation val assertOp: ContentProviderOperation.Builder = ContentProviderOperation.newAssertQuery(rawContactUri).apply { // Adds the assertions to the assert operation: checks the version withValue(SyncColumns.VERSION, mVersion) // and count of rows tested withExpectedCount(1) } // Creates an ArrayList to hold the ContentProviderOperation objects val ops = arrayListOf<ContentProviderOperation>() ops.add(assertOp.build()) // You would add the rest of your batch operations to "ops" here ... // Applies the batch. If the assert fails, an Exception is thrown try { val results: Array<ContentProviderResult> = contentResolver.applyBatch(AUTHORITY, ops) } catch (e: OperationApplicationException) { // Actions you want to take if the assert operation fails go here }
Ява
/* * The application uses CursorLoader to query the raw contacts table. The system calls this method * when the load is finished. */ public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Gets the raw contact's _ID and VERSION values rawContactID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)); mVersion = cursor.getInt(cursor.getColumnIndex(SyncColumns.VERSION)); } ... // Sets up a Uri for the assert operation Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactID); // Creates a builder for the assert operation ContentProviderOperation.Builder assertOp = ContentProviderOperation.newAssertQuery(rawContactUri); // Adds the assertions to the assert operation: checks the version and count of rows tested assertOp.withValue(SyncColumns.VERSION, mVersion); assertOp.withExpectedCount(1); // Creates an ArrayList to hold the ContentProviderOperation objects ArrayList ops = new ArrayList<ContentProviderOperation>; ops.add(assertOp.build()); // You would add the rest of your batch operations to "ops" here ... // Applies the batch. If the assert fails, an Exception is thrown try { ContentProviderResult[] results = getContentResolver().applyBatch(AUTHORITY, ops); } catch (OperationApplicationException e) { // Actions you want to take if the assert operation fails go here }
Retrieval and modification with intents
Sending an intent to the device's contacts application allows you to access the Contacts Provider indirectly. The intent starts the device's contacts application UI, in which users can do contacts-related work. With this type of access, users can:
- Pick a contact from a list and have it returned to your app for further work.
- Edit an existing contact's data.
- Insert a new raw contact for any of their accounts.
- Delete a contact or contacts data.
If the user is inserting or updating data, you can collect the data first and send it as part of the intent.
When you use intents to access the Contacts Provider via the device's contacts application, you don't have to write your own UI or code for accessing the provider. You also don't have to request permission to read or write to the provider. The device's contacts application can delegate read permission for a contact to you, and because you're making modifications to the provider through another application, you don't have to have write permissions.
The general process of sending an intent to access a provider is described in detail in the Content Provider basics guide in the section "Data access via intents." The action, MIME type, and data values you use for the available tasks are summarized in Table 4, while the extras values you can use with putExtra() are listed in the reference documentation for ContactsContract.Intents.Insert :
Table 4. Contacts Provider Intents.
| Задача | Действие | Данные | MIME-тип | Примечания |
|---|---|---|---|---|
| Pick a contact from a list | ACTION_PICK | Один из:
| Не используется | Displays a list of raw contacts or a list of data from a raw contact, depending on the content URI type you supply. Call |
| Insert a new raw contact | Insert.ACTION | Н/Д | RawContacts.CONTENT_TYPE , MIME type for a set of raw contacts. | Displays the device's contacts application's Add Contact screen. The extras values you add to the intent are displayed. If sent with startActivityForResult() , the content URI of the newly-added raw contact is passed back to your activity's onActivityResult() callback method in the Intent argument, in the "data" field. To get the value, call getData() . |
| Редактировать контакт | ACTION_EDIT | CONTENT_LOOKUP_URI for the contact. The editor activity will allow the user to edit any of the data associated with this contact. | Contacts.CONTENT_ITEM_TYPE , a single contact. | Displays the Edit Contact screen in the contacts application. The extras values you add to the intent are displayed. When the user clicks Done to save the edits, your activity returns to the foreground. |
| Display a picker that can also add data. | ACTION_INSERT_OR_EDIT | Н/Д | CONTENT_ITEM_TYPE | This intent always displays the contacts app's picker screen. The user can either pick a contact to edit, or add a new contact. Either the edit or the add screen appears, depending on the user's choice, and the extras data you pass in the intent is displayed. If your app displays contact data such as an email or phone number, use this intent to allow the user to add the data to an existing contact. contact, Note: There's no need to send a name value in this intent's extras, because the user always picks an existing name or adds a new one. Moreover, if you send a name, and the user chooses to do an edit, the contacts app will display the name you send, overwriting the previous value. If the user doesn't notice this and saves the edit, the old value is lost. |
The device's contacts app doesn't allow you to delete a raw contact or any of its data with an intent. Instead, to delete a raw contact, use ContentResolver.delete() or ContentProviderOperation.newDelete() .
The following snippet shows how to construct and send an intent that inserts a new raw contact and data:
Котлин
// Gets values from the UI val name = contactNameEditText.text.toString() val phone = contactPhoneEditText.text.toString() val email = contactEmailEditText.text.toString() val company = companyName.text.toString() val jobtitle = jobTitle.text.toString() /* * Demonstrates adding data rows as an array list associated with the DATA key */ // Defines an array list to contain the ContentValues objects for each row val contactData = arrayListOf<ContentValues>() /* * Defines the raw contact row */ // Sets up the row as a ContentValues object val rawContactRow = ContentValues().apply { // Adds the account type and name to the row put(ContactsContract.RawContacts.ACCOUNT_TYPE, selectedAccount.type) put(ContactsContract.RawContacts.ACCOUNT_NAME, selectedAccount.name) } // Adds the row to the array contactData.add(rawContactRow) /* * Sets up the phone number data row */ // Sets up the row as a ContentValues object val phoneRow = ContentValues().apply { // Specifies the MIME type for this data row (all data rows must be marked by their type) put(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) // Adds the phone number and its type to the row put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone) } // Adds the row to the array contactData.add(phoneRow) /* * Sets up the email data row */ // Sets up the row as a ContentValues object val emailRow = ContentValues().apply { // Specifies the MIME type for this data row (all data rows must be marked by their type) put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) // Adds the email address and its type to the row put(ContactsContract.CommonDataKinds.Email.ADDRESS, email) } // Adds the row to the array contactData.add(emailRow) // Creates a new intent for sending to the device's contacts application val insertIntent = Intent(ContactsContract.Intents.Insert.ACTION).apply { // Sets the MIME type to the one expected by the insertion activity type = ContactsContract.RawContacts.CONTENT_TYPE // Sets the new contact name putExtra(ContactsContract.Intents.Insert.NAME, name) // Sets the new company and job title putExtra(ContactsContract.Intents.Insert.COMPANY, company) putExtra(ContactsContract.Intents.Insert.JOB_TITLE, jobtitle) /* * Adds the array to the intent's extras. It must be a parcelable object in order to * travel between processes. The device's contacts app expects its key to be * Intents.Insert.DATA */ putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, contactData) } // Send out the intent to start the device's contacts app in its add contact activity. startActivity(insertIntent)
Ява
// Gets values from the UI String name = contactNameEditText.getText().toString(); String phone = contactPhoneEditText.getText().toString(); String email = contactEmailEditText.getText().toString(); String company = companyName.getText().toString(); String jobtitle = jobTitle.getText().toString(); // Creates a new intent for sending to the device's contacts application Intent insertIntent = new Intent(ContactsContract.Intents.Insert.ACTION); // Sets the MIME type to the one expected by the insertion activity insertIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE); // Sets the new contact name insertIntent.putExtra(ContactsContract.Intents.Insert.NAME, name); // Sets the new company and job title insertIntent.putExtra(ContactsContract.Intents.Insert.COMPANY, company); insertIntent.putExtra(ContactsContract.Intents.Insert.JOB_TITLE, jobtitle); /* * Demonstrates adding data rows as an array list associated with the DATA key */ // Defines an array list to contain the ContentValues objects for each row ArrayList<ContentValues> contactData = new ArrayList<ContentValues>(); /* * Defines the raw contact row */ // Sets up the row as a ContentValues object ContentValues rawContactRow = new ContentValues(); // Adds the account type and name to the row rawContactRow.put(ContactsContract.RawContacts.ACCOUNT_TYPE, selectedAccount.getType()); rawContactRow.put(ContactsContract.RawContacts.ACCOUNT_NAME, selectedAccount.getName()); // Adds the row to the array contactData.add(rawContactRow); /* * Sets up the phone number data row */ // Sets up the row as a ContentValues object ContentValues phoneRow = new ContentValues(); // Specifies the MIME type for this data row (all data rows must be marked by their type) phoneRow.put( ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE ); // Adds the phone number and its type to the row phoneRow.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone); // Adds the row to the array contactData.add(phoneRow); /* * Sets up the email data row */ // Sets up the row as a ContentValues object ContentValues emailRow = new ContentValues(); // Specifies the MIME type for this data row (all data rows must be marked by their type) emailRow.put( ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ); // Adds the email address and its type to the row emailRow.put(ContactsContract.CommonDataKinds.Email.ADDRESS, email); // Adds the row to the array contactData.add(emailRow); /* * Adds the array to the intent's extras. It must be a parcelable object in order to * travel between processes. The device's contacts app expects its key to be * Intents.Insert.DATA */ insertIntent.putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, contactData); // Send out the intent to start the device's contacts app in its add contact activity. startActivity(insertIntent);
Целостность данных
Because the contacts repository contains important and sensitive data that users expect to be correct and up-to-date, the Contacts Provider has well-defined rules for data integrity. It's your responsibility to conform to these rules when you modify contacts data. The important rules are listed here:
- Always add a
ContactsContract.CommonDataKinds.StructuredNamerow for everyContactsContract.RawContactsrow you add. - A
ContactsContract.RawContactsrow without aContactsContract.CommonDataKinds.StructuredNamerow in theContactsContract.Datatable may cause problems during aggregation. - Always link new
ContactsContract.Datarows to their parentContactsContract.RawContactsrow. - A
ContactsContract.Datarow that isn't linked to aContactsContract.RawContactswon't be visible in the device's contacts application, and it might cause problems with sync adapters. - Change data only for those raw contacts that you own.
- Remember that the Contacts Provider is usually managing data from several different account types/online services. You need to ensure that your application only modifies or deletes data for rows that belong to you, and that it only inserts data with an account type and name that you control.
- Always use the constants defined in
ContactsContractand its subclasses for authorities, content URIs, URI paths, column names, MIME types, andTYPEvalues. - Using these constants helps you to avoid errors. You'll also be notified with compiler warnings if any of the constants is deprecated.
Custom data rows
By creating and using your own custom MIME types, you can insert, edit, delete, and retrieve your own data rows in the ContactsContract.Data table. Your rows are limited to using the column defined in ContactsContract.DataColumns , although you can map your own type-specific column names to the default column names. In the device's contacts application, the data for your rows is displayed but can't be edited or deleted, and users can't add additional data. To allow users to modify your custom data rows, you must provide an editor activity in your own application.
To display your custom data, provide a contacts.xml file containing a <ContactsAccountType> element and one or more of its <ContactsDataKind> child elements. This is described in more detail in the section <ContactsDataKind> element .
To learn more about custom MIME types, read the Create a Content Provider guide.
Contacts Provider sync adapters
The Contacts Provider is specifically designed for handling synchronization of contacts data between a device and an online service. This allows users to download existing data to a new device and upload existing data to a new account. Synchronization also ensures that users have the latest data at hand, regardless of the source of additions and changes. Another advantage of synchronization is that it makes contacts data available even when the device is not connected to the network.
Although you can implement synchronization in a variety of ways, the Android system provides a plug-in synchronization framework that automates the following tasks:
- Checking network availability.
- Scheduling and executing synchronization, based on user preferences.
- Restarting synchronizations that have stopped.
To use this framework, you supply a sync adapter plug-in. Each sync adapter is unique to a service and content provider, but can handle multiple account names for the same service. The framework also allows multiple sync adapters for the same service and provider.
Sync adapter classes and files
You implement a sync adapter as a subclass of AbstractThreadedSyncAdapter and install it as part of an Android application. The system learns about the sync adapter from elements in your application manifest, and from a special XML file pointed to by the manifest. The XML file defines the account type for the online service and the authority for the content provider, which together uniquely identify the adapter. The sync adapter does not become active until the user adds an account for the sync adapter's account type and enables synchronization for the content provider the sync adapter syncs with. At that point, the system starts managing the adapter, calling it as necessary to synchronize between the content provider and the server.
Note: Using an account type as part of the sync adapter's identification allows the system to detect and group together sync adapters that access different services from the same organization. For example, sync adapters for Google online services all have the same account type com.google . When users add a Google Account to their devices, all of the installed sync adapters for Google services are listed together; each sync adapter listed syncs with a different content provider on the device.
Because most services require users to verify their identity before accessing data, the Android system offers an authentication framework that is similar to, and often used in conjunction with, the sync adapter framework. The authentication framework uses plug-in authenticators that are subclasses of AbstractAccountAuthenticator . An authenticator verifies the user's identity in the following steps:
- Collects the user's name, password or similar information (the user's credentials ).
- Sends the credentials to the service
- Examines the service's reply.
If the service accepts the credentials, the authenticator can store the credentials for later use. Because of the plug-in authenticator framework, the AccountManager can provide access to any authtokens an authenticator supports and chooses to expose, such as OAuth2 authtokens.
Although authentication is not required, most contacts services use it. However, you're not required to use the Android authentication framework to do authentication.
Sync adapter implementation
To implement a sync adapter for the Contacts Provider, you start by creating an Android application that contains the following:
- A
Servicecomponent that responds to requests from the system to bind to the sync adapter. - When the system wants to run a synchronization, it calls the service's
onBind()method to get anIBinderfor the sync adapter. This allows the system to do cross-process calls to the adapter's methods. - The actual sync adapter, implemented as a concrete subclass of
AbstractThreadedSyncAdapter. - This class does the work of downloading data from the server, uploading data from the device, and resolving conflicts. The main work of the adapter is done in the method
onPerformSync(). This class must be instantiated as a singleton. - A subclass of
Application. - This class acts as a factory for the sync adapter singleton. Use the
onCreate()method to instantiate the sync adapter, and provide a static "getter" method to return the singleton to theonBind()method of the sync adapter's service. - Optional: A
Servicecomponent that responds to requests from the system for user authentication. -
AccountManagerstarts this service to begin the authentication process. The service'sonCreate()method instantiates an authenticator object. When the system wants to authenticate a user account for the application's sync adapter, it calls the service'sonBind()method to get anIBinderfor the authenticator. This allows the system to do cross-process calls to the authenticator's methods.. - Optional: A concrete subclass of
AbstractAccountAuthenticatorthat handles requests for authentication. - This class provides methods that the
AccountManagerinvokes to authenticate the user's credentials with the server. The details of the authentication process vary widely, based on the server technology in use. You should refer to the documentation for your server software to learn more about authentication. - XML files that define the sync adapter and authenticator to the system.
- The sync adapter and authenticator service components described previously are defined in
< service >elements in the application manifest. These elements contain< meta-data >child elements that provide specific data to the system:- The
< meta-data >element for the sync adapter service points to the XML fileres/xml/syncadapter.xml. In turn, this file specifies a URI for the web service that will be synchronized with the Contacts Provider, and an account type for the web service. - Optional: The
< meta-data >element for the authenticator points to the XML fileres/xml/authenticator.xml. In turn, this file specifies the account type that this authenticator supports, as well as UI resources that appear during the authentication process. The account type specified in this element must be the same as the account type specified for the sync adapter.
- The
Social stream data
The android.provider.ContactsContract.StreamItems and android.provider.ContactsContract.StreamItemPhotos tables manage incoming data from social networks. You can write a sync adapter that adds stream data from your own network to these tables, or you can read stream data from these tables and display it in your own application, or both. With these features, your social networking services and applications can be integrated into Android's social networking experience.
Social stream text
Stream items are always associated with a raw contact. The android.provider.ContactsContract.StreamItemsColumns#RAW_CONTACT_ID links to the _ID value for the raw contact. The account type and account name of the raw contact are also stored in the stream item row.
Store the data from your stream in the following columns:
- android.provider.ContactsContract.StreamItemsColumns#ACCOUNT_TYPE
- Required. The user's account type for the raw contact associated with this stream item. Remember to set this value when you insert a stream item.
- android.provider.ContactsContract.StreamItemsColumns#ACCOUNT_NAME
- Required. The user's account name for the raw contact associated with this stream item. Remember to set this value when you insert a stream item.
- Identifier columns
- Required. You must insert the following identifier columns when you insert a stream item:
- android.provider.ContactsContract.StreamItemsColumns#CONTACT_ID: The android.provider.BaseColumns#_ID value of the contact that this stream item is associated with.
- android.provider.ContactsContract.StreamItemsColumns#CONTACT_LOOKUP_KEY: The android.provider.ContactsContract.ContactsColumns#LOOKUP_KEY value of the contact this stream item is associated with.
- android.provider.ContactsContract.StreamItemsColumns#RAW_CONTACT_ID: The android.provider.BaseColumns#_ID value of the raw contact that this stream item is associated with.
- android.provider.ContactsContract.StreamItemsColumns#COMMENTS
- Optional. Stores summary information that you can display at the beginning of a stream item.
- android.provider.ContactsContract.StreamItemsColumns#TEXT
- The text of the stream item, either the content that was posted by the source of the item, or a description of some action that generated the stream item. This column can contain any formatting and embedded resource images that can be rendered by
fromHtml(). The provider may truncate or ellipsize long content, but it will try to avoid breaking tags. - android.provider.ContactsContract.StreamItemsColumns#TIMESTAMP
- A text string containing the time the stream item was inserted or updated, in the form of milliseconds since epoch. Applications that insert or update stream items are responsible for maintaining this column; it is not automatically maintained by the Contacts Provider.
To display identifying information for your stream items, use the android.provider.ContactsContract.StreamItemsColumns#RES_ICON, android.provider.ContactsContract.StreamItemsColumns#RES_LABEL, and android.provider.ContactsContract.StreamItemsColumns#RES_PACKAGE to link to resources in your application.
The android.provider.ContactsContract.StreamItems table also contains the columns android.provider.ContactsContract.StreamItemsColumns#SYNC1 through android.provider.ContactsContract.StreamItemsColumns#SYNC4 for the exclusive use of sync adapters.
Social stream photos
The android.provider.ContactsContract.StreamItemPhotos table stores photos associated with a stream item. The table's android.provider.ContactsContract.StreamItemPhotosColumns#STREAM_ITEM_ID column links to values in the _ID column of android.provider.ContactsContract.StreamItems table. Photo references are stored in the table in these columns:
- android.provider.ContactsContract.StreamItemPhotos#PHOTO column (a BLOB).
- A binary representation of the photo, resized by the provider for storage and display. This column is available for backwards compatibility with previous versions of the Contacts Provider that used it for storing photos. However, in the current version you should not use this column to store photos. Instead, use either android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_FILE_ID or android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_URI (both of which are described in the following points) to store photos in a file. This column now contains a thumbnail of the photo, which is available for reading.
- android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_FILE_ID
- A numeric identifier of a photo for a raw contact. Append this value to the constant
DisplayPhoto.CONTENT_URIto get a content URI pointing to a single photo file, and then callopenAssetFileDescriptor()to get a handle to the photo file. - android.provider.ContactsContract.StreamItemPhotosColumns#PHOTO_URI
- A content URI pointing directly to the photo file for the photo represented by this row. Call
openAssetFileDescriptor()with this URI to get a handle to the photo file.
Using the social stream tables
These tables work the same as the other main tables in the Contacts Provider, except that:
- These tables require additional access permissions. To read from them, your application must have the permission android.Manifest.permission#READ_SOCIAL_STREAM. To modify them, your application must have the permission android.Manifest.permission#WRITE_SOCIAL_STREAM.
- For the android.provider.ContactsContract.StreamItems table, the number of rows stored for each raw contact is limited. Once this limit is reached, the Contacts Provider makes space for new stream item rows by automatically deleting the rows having the oldest android.provider.ContactsContract.StreamItemsColumns#TIMESTAMP. To get the limit, issue a query to the content URI android.provider.ContactsContract.StreamItems#CONTENT_LIMIT_URI. You can leave all the arguments other than the content URI set to
null. The query returns a Cursor containing a single row, with the single column android.provider.ContactsContract.StreamItems#MAX_ITEMS.
The class android.provider.ContactsContract.StreamItems.StreamItemPhotos defines a sub-table of android.provider.ContactsContract.StreamItemPhotos containing the photo rows for a single stream item.
Social stream interactions
The social stream data managed by the Contacts Provider, in conjunction with the device's contacts application, offers a powerful way to connect your social networking system with existing contacts. The following features are available:
- By syncing your social networking service to the Contacts Provider with a sync adapter, you can retrieve recent activity for a user's contacts and store it in the android.provider.ContactsContract.StreamItems and android.provider.ContactsContract.StreamItemPhotos tables for later use.
- Besides regular synchronization, you can trigger your sync adapter to retrieve additional data when the user selects a contact to view. This allows your sync adapter to retrieve high-resolution photos and the most recent stream items for the contact.
- By registering a notification with the device's contacts application and the Contacts Provider, you can receive an intent when a contact is viewed, and at that point update the contact's status from your service. This approach may be faster and use less bandwidth than doing a full sync with a sync adapter.
- Users can add a contact to your social networking service while looking at the contact in the device's contacts application. You enable this with the "invite contact" feature, which you enable with a combination of an activity that adds an existing contact to your network, and an XML file that provides the device's contacts application and the Contacts Provider with the details of your application.
Regular synchronization of stream items with the Contacts Provider is the same as other synchronizations. To learn more about synchronization, see the section Contacts Provider sync adapters . Registering notifications and inviting contacts are covered in the next two sections.
Registering to handle social networking views
To register your sync adapter to receive notifications when the user views a contact that's managed by your sync adapter:
- Create a file named
contacts.xmlin your project'sres/xml/directory. If you already have this file, you can skip this step. - In this file, add the element
<ContactsAccountType xmlns:android="http://schemas.android.com/apk/res/android">. If this element already exists, you can skip this step. - To register a service that is notified when the user opens a contact's detail page in the device's contacts application, add the attribute
viewContactNotifyService=" serviceclass "to the element, whereserviceclassis the fully-qualified classname of the service that should receive the intent from the device's contacts application. For the notifier service, use a class that extendsIntentService, to allow the service to receive intents. The data in the incoming intent contains the content URI of the raw contact the user clicked. From the notifier service, you can bind to and then call your sync adapter to update the data for the raw contact.
To register an activity to be called when the user clicks on a stream item or photo or both:
- Create a file named
contacts.xmlin your project'sres/xml/directory. If you already have this file, you can skip this step. - In this file, add the element
<ContactsAccountType xmlns:android="http://schemas.android.com/apk/res/android">. If this element already exists, you can skip this step. - To register one of your activities to handle the user clicking on a stream item in the device's contacts application, add the attribute
viewStreamItemActivity=" activityclass "to the element, whereactivityclassis the fully-qualified classname of the activity that should receive the intent from the device's contacts application. - To register one of your activities to handle the user clicking on a stream photo in the device's contacts application, add the attribute
viewStreamItemPhotoActivity=" activityclass "to the element, whereactivityclassis the fully-qualified classname of the activity that should receive the intent from the device's contacts application.
The <ContactsAccountType> element is described in more detail in the section <ContactsAccountType> element .
The incoming intent contains the content URI of the item or photo that the user clicked. To have separate activities for text items and for photos, use both attributes in the same file.
Interacting with your social networking service
Users don't have to leave the device's contacts application to invite a contact to your social networking site. Instead, you can have the device's contacts app send an intent for inviting the contact to one of your activities. To set this up:
- Create a file named
contacts.xmlin your project'sres/xml/directory. If you already have this file, you can skip this step. - In this file, add the element
<ContactsAccountType xmlns:android="http://schemas.android.com/apk/res/android">. If this element already exists, you can skip this step. - Add the following attributes:
-
inviteContactActivity=" activityclass " -
inviteContactActionLabel="@string/ invite_action_label "
activityclassvalue is the fully-qualified classname of the activity that should receive the intent. Theinvite_action_labelvalue is a text string that's displayed in the Add Connection menu in the device's contacts application. -
Note: ContactsSource is a deprecated tag name for ContactsAccountType .
contacts.xml reference
The file contacts.xml contains XML elements that control the interaction of your sync adapter and application with the contacts application and the Contacts Provider. These elements are described in the following sections.
<ContactsAccountType> element
The <ContactsAccountType> element controls the interaction of your application with the contacts application. It has the following syntax:
<ContactsAccountType xmlns:android="http://schemas.android.com/apk/res/android" inviteContactActivity="activity_name" inviteContactActionLabel="invite_command_text" viewContactNotifyService="view_notify_service" viewGroupActivity="group_view_activity" viewGroupActionLabel="group_action_text" viewStreamItemActivity="viewstream_activity_name" viewStreamItemPhotoActivity="viewphotostream_activity_name">
contained in:
res/xml/contacts.xml
can contain:
<ContactsDataKind>
Описание:
Declares Android components and UI labels that allow users to invite one of their contacts to a social network, notify users when one of their social networking streams is updated, and so forth.
Notice that the attribute prefix android: is not necessary for the attributes of <ContactsAccountType> .
Атрибуты:
-
inviteContactActivity - The fully-qualified class name of the activity in your application that you want to activate when the user selects Add connection from the device's contacts application.
-
inviteContactActionLabel - A text string that is displayed for the activity specified in
inviteContactActivity, in the Add connection menu. For example, you can use the string "Follow in my network". You can use a string resource identifier for this label. -
viewContactNotifyService - The fully-qualified class name of a service in your application that should receive notifications when the user views a contact. This notification is sent by the device's contacts application; it allows your application to postpone data-intensive operations until they're needed. For example, your application can respond to this notification by reading in and displaying the contact's high-resolution photo and most recent social stream items. This feature is described in more detail in the section Social stream interactions .
-
viewGroupActivity - The fully-qualified class name of an activity in your application that can display group information. When the user clicks the group label in the device's contacts application, the UI for this activity is displayed.
-
viewGroupActionLabel - The label that the contacts application displays for a UI control that allows the user to look at groups in your application.
A string resource identifier is allowed for this attribute.
-
viewStreamItemActivity - The fully-qualified class name of an activity in your application that the device's contacts application launches when the user clicks a stream item for a raw contact.
-
viewStreamItemPhotoActivity - The fully-qualified class name of an activity in your application that the device's contacts application launches when the user clicks a photo in the stream item for a raw contact.
<ContactsDataKind> element
The <ContactsDataKind> element controls the display of your application's custom data rows in the contacts application's UI. It has the following syntax:
<ContactsDataKind android:mimeType="MIMEtype" android:icon="icon_resources" android:summaryColumn="column_name" android:detailColumn="column_name">
contained in:
<ContactsAccountType>Описание:
Use this element to have the contacts application display the contents of a custom data row as part of the details of a raw contact. Each <ContactsDataKind> child element of <ContactsAccountType> represents a type of custom data row that your sync adapter adds to the ContactsContract.Data table. Add one <ContactsDataKind> element for each custom MIME type you use. You don't have to add the element if you have a custom data row for which you don't want to display data.
Атрибуты:
-
android:mimeType - The custom MIME type you've defined for one of your custom data row types in the
ContactsContract.Datatable. For example, the valuevnd.android.cursor.item/vnd.example.locationstatuscould be a custom MIME type for a data row that records a contact's last known location. -
android:icon - An Android drawable resource that the contacts application displays next to your data. Use this to indicate to the user that the data comes from your service.
-
android:summaryColumn - The column name for the first of two values retrieved from the data row. The value is displayed as the first line of the entry for this data row. The first line is intended to be used as a summary of the data, but that is optional. See also android:detailColumn .
-
android:detailColumn - The column name for the second of two values retrieved from the data row. The value is displayed as the second line of the entry for this data row. See also
android:summaryColumn.
Additional Contacts Provider features
Besides the main features described in previous sections, the Contacts Provider offers these useful features for working with contacts data:
- Контактные группы
- Фото особенности
Контактные группы
The Contacts Provider can optionally label collections of related contacts with group data. If the server associated with a user account wants to maintain groups, the sync adapter for the account's account type should transfer groups data between the Contacts Provider and the server. When users add a new contact to the server and then put this contact in a new group, the sync adapter must add the new group to the ContactsContract.Groups table. The group or groups a raw contact belongs to are stored in the ContactsContract.Data table, using the ContactsContract.CommonDataKinds.GroupMembership MIME type.
If you're designing a sync adapter that will add raw contact data from server to the Contacts Provider, and you aren't using groups, then you need to tell the Provider to make your data visible. In the code that is executed when a user adds an account to the device, update the ContactsContract.Settings row that the Contacts Provider adds for the account. In this row, set the value of the Settings.UNGROUPED_VISIBLE column to 1. When you do this, the Contacts Provider will always make your contacts data visible, even if you don't use groups.
Контактные фотографии
The ContactsContract.Data table stores photos as rows with MIME type Photo.CONTENT_ITEM_TYPE . The row's CONTACT_ID column is linked to the _ID column of the raw contact to which it belongs. The class ContactsContract.Contacts.Photo defines a sub-table of ContactsContract.Contacts containing photo information for a contact's primary photo, which is the primary photo of the contact's primary raw contact. Similarly, the class ContactsContract.RawContacts.DisplayPhoto defines a sub-table of ContactsContract.RawContacts containing photo information for a raw contact's primary photo.
The reference documentation for ContactsContract.Contacts.Photo and ContactsContract.RawContacts.DisplayPhoto contain examples of retrieving photo information. There is no convenience class for retrieving the primary thumbnail for a raw contact, but you can send a query to the ContactsContract.Data table, selecting on the raw contact's _ID , the Photo.CONTENT_ITEM_TYPE , and the IS_PRIMARY column to find the raw contact's primary photo row.
Social stream data for a person may also include photos. These are stored in the android.provider.ContactsContract.StreamItemPhotos table, which is described in more detail in the section Social stream photos .