How To create new contact in .net MAUI

Pearl 41 Reputation points
2024-07-28T18:21:37.05+00:00

Hi,

I want to add new contact in .NET maui. Can you please help me? I am trying to create API for both android and iphone. My .net version. is 8.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,244 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 72,491 Reputation points Microsoft Vendor
    2024-07-30T06:12:56.75+00:00

    Hello,

    Can you please share some example of ContentProviderOperation.NewInsert ?

    Sure, before you insert contact, please add following permission in the AndroidManifest.xml for Android.

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    

    Then, you can request this permission by Permissions.RequestAsync<Permissions.ContactsWrite>();. If the permission is granted, you can insert contacts information.

         PermissionStatus status = await Permissions.RequestAsync<Permissions.ContactsWrite>();           
                if (status == PermissionStatus.Granted)
                {
    #if ANDROID
    
       Context context = Platform.AppContext;
     
                /* Add data to raw_contacts and get the added ID number*/
                Android.Net.Uri uri = Android.Net.Uri.Parse("content://com.android.contacts/raw_contacts");
                ContentResolver resolver = context.ContentResolver;
                ContentValues values = new ContentValues();
                long contactId = ContentUris.ParseId(resolver.Insert(uri, values));
     
               
                // Add Name MyTestName for testing.
                uri = Android.Net.Uri.Parse("content://com.android.contacts/data");
                values.Put("raw_contact_id", contactId);
                values.Put("mimetype", "vnd.android.cursor.item/name");
                values.Put("data2", "MyTestName");
                resolver.Insert(uri, values);
     
                // Add telephone Numer 1234579 for testing
                values.Clear();
                values.Put("raw_contact_id", contactId);
                values.Put("mimetype", "vnd.android.cursor.item/phone_v2");
                values.Put("data2", "2");
                values.Put("data1", "1234579");
                resolver.Insert(uri, values);
    #endif
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments