I am using this Xamarin.Mobile component in Xamarin.Android project. After a lot of googling and going through their samples, i found only the way to retrieve the contacts from phone to my app.
Below is my code:
AddressBook book = new AddressBook(context)
{
PreferContactAggregation = true
};
Phone ph = new Phone(){
Type = PhoneType.Mobile,
Number = "9952429044"
};
Contact ct = new Contact()
{
DisplayName = "Sai Ram",
FirstName = "Om",
MiddleName = "Sai",
LastName = "Ram",
Phones = new List<Phone>(){ph}
};
I need to save the Contact object to the phone's addressbook. I can't find any methods like book.Save(contact)
in Xamarin.Contacts
.
Xamarin.Mobile has API only for reading contacts, not for adding.
EDIT
Here is short sample of how to add new contact with mobile number to your contacts.
List<ContentProviderOperation> ops = new List<ContentProviderOperation>();
int rawContactInsertIndex = ops.Count;
ops.Add(ContentProviderOperation.NewInsert(Android.Provider.ContactsContract.RawContacts.ContentUri)
.WithValue(Android.Provider.ContactsContract.RawContacts.InterfaceConsts.AccountType, null)
.WithValue(Android.Provider.ContactsContract.RawContacts.InterfaceConsts.AccountName, null).Build());
ops.Add(ContentProviderOperation
.NewInsert(Android.Provider.ContactsContract.Data.ContentUri)
.WithValueBackReference(Android.Provider.ContactsContract.Data.InterfaceConsts.RawContactId,rawContactInsertIndex)
.WithValue(Android.Provider.ContactsContract.Data.InterfaceConsts.Mimetype, Android.Provider.ContactsContract.CommonDataKinds.StructuredName.ContentItemType)
.WithValue(Android.Provider.ContactsContract.CommonDataKinds.StructuredName.DisplayName, "Vikas Patidar") // Name of the person
.Build());
ops.Add(ContentProviderOperation
.NewInsert(Android.Provider.ContactsContract.Data.ContentUri)
.WithValueBackReference(
ContactsContract.Data.InterfaceConsts.RawContactId, rawContactInsertIndex)
.WithValue(Android.Provider.ContactsContract.Data.InterfaceConsts.Mimetype, Android.Provider.ContactsContract.CommonDataKinds.Phone.ContentItemType)
.WithValue(Android.Provider.ContactsContract.CommonDataKinds.Phone.Number, "9999999999") // Number of the person
.WithValue(Android.Provider.ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type, "mobile").Build()); // Type of mobile number
// Asking the Contact provider to create a new contact
try {
ContentResolver.ApplyBatch(ContactsContract.Authority, ops);
} catch (Exception ex) {
Toast.MakeText(this, "Exception: " + ex.Message, ToastLength.Long).Show();
}
You can find more details about how to save other fields here . Don't forget to add WRITE_CONTACTS permission to your app.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.