使用者設定檔

自 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)開始, ContactsContact.Profile 類別可透過 ContactsContract 提供者取得。 ContactsContact.Profile提供裝置擁有者個人配置檔的存取權,其中包括聯繫人數據,例如裝置擁有者的名稱和電話號碼。

必要權限

若要讀取和寫入聯繫人數據,應用程式必須分別要求 READ_CONTACTSWRITE_CONTACTS 許可權。 此外,若要讀取和編輯使用者配置檔,應用程式必須要求 READ_PROFILEWRITE_PROFILE 許可權。

更新配置檔數據

設定這些許可權之後,應用程式就可以使用一般 Android 技術來與使用者配置檔的數據互動。 例如,若要更新配置文件的顯示名稱,請使用透過 ContactsContract.Profile.ContentRawContactsUri 屬性擷取的 呼叫 ContentResolver.UpdateUri,如下所示:

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

執行上述程式代碼時,使用者設定檔會顯示如下螢幕快照所示:

顯示 John Doe 使用者設定檔的設定檔螢幕快照

使用使用者配置檔類似於與 Android 中的其他資料互動,並提供額外的裝置個人化層級。