用户配置文件

自 API 级别 5 以来,Android 已支持使用 ContactsContract 提供程序枚举联系人。 例如,列出联系人与使用 ContactContracts.Contacts 类一样简单,如以下代码示例所示:

// Get the URI for the user's contacts:
var uri = ContactsContract.Contacts.ContentUri;

// Setup the "projection" (columns we want) for only the ID and display name:
string[] projection = {
    ContactsContract.Contacts.InterfaceConsts.Id,
    ContactsContract.Contacts.InterfaceConsts.DisplayName };

// Use a CursorLoader to retrieve the user's contacts data:
CursorLoader loader = new CursorLoader(this, uri, projection, null, null, null);
ICursor cursor = (ICursor)loader.LoadInBackground();

// Print the contact data to the console if reading back succeeds:
if (cursor != null)
{
    if (cursor.MoveToFirst())
    {
        do
        {
            Console.WriteLine("Contact ID: {0}, Contact Name: {1}",
                               cursor.GetString(cursor.GetColumnIndex(projection[0])),
                               cursor.GetString(cursor.GetColumnIndex(projection[1])));
        } while (cursor.MoveToNext());
    }
}

从 Android 4(API 级别 14 开始),可通过 ContactsContract 提供程序获得 ContactsContact.Profile 类。 ContactsContact.Profile 提供对设备所有者的个人配置文件的访问权限,其中包括联系人数据,例如设备所有者的姓名和电话号码。

所需的权限

若要读取和写入联系人数据,应用程序必须分别请求 READ_CONTACTSWRITE_CONTACTS 权限。 此外,若要读取和编辑用户配置文件,应用程序必须请求 READ_PROFILEWRITE_PROFILE 权限。

更新配置文件数据

设置这些权限后,应用程序可以使用正常的 Android 技术与用户配置文件的数据进行交互。 例如,若要更新配置文件的显示名称,请使用通过 ContactsContract.Profile.ContentRawContactsUri 属性检索 Uri 调用 ContentResolver.Update,如下所示:

var values = new ContentValues ();
values.Put (ContactsContract.Contacts.InterfaceConsts.DisplayName, "John Doe");

// Update the user profile with the name "John Doe":
ContentResolver.Update (ContactsContract.Profile.ContentRawContactsUri, values, null, null);

读取配置文件数据

ContactsContact.Profile.ContentUri 发出查询会读取配置文件数据。 例如,以下代码将读取用户配置文件的显示名称:

// Read the profile
var uri = ContactsContract.Profile.ContentUri;

// Setup the "projection" (column we want) for only the display name:
string[] projection = {
    ContactsContract.Contacts.InterfaceConsts.DisplayName };

// Use a CursorLoader to retrieve the data:
CursorLoader loader = new CursorLoader(this, uri, projection, null, null, null);
ICursor cursor = (ICursor)loader.LoadInBackground();
if (cursor != null)
{
    if (cursor.MoveToFirst ())
    {
        Console.WriteLine(cursor.GetString (cursor.GetColumnIndex (projection [0])));
    }
}

最后,若要导航到用户配置文件,请使用 ActionView 操作创建意向,然后 ContactsContract.Profile.ContentUri 会将其传递给 StartActivity 方法,如下所示:

var intent = new Intent (Intent.ActionView,
    ContactsContract.Profile.ContentUri);
StartActivity (intent);

运行上述代码时,用户配置文件会如下屏幕截图所示进行显示:

Screenshot of profile displaying the John Doe user profile

使用用户配置文件类似于与 Android 中的其他数据交互,并会提供额外的设备个性化级别。