androidandroid-contacts

Adding a new contact as Google contact and not on local device


I have an app that can save new contacts on the device, but I want to be able to save the contact on Google contacts, if the user chooses so, or if these are the default settings. Does someone know how to do it? (I can't find anything on the web).

This is the code for saving on the device:

 ArrayList<ContentProviderOperation> data = new ArrayList<ContentProviderOperation>();

                        data.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                                .withValue(ContactsContract.RawContacts.CONTACT_ID, null)
                                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                                .build());

                        //---------Name
                        data.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
                                .build());

                        //---------Phone
                        data.add(ContentProviderOperation.
                                newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone)
                                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                                .build());

                        try {
                           getContentResolver().applyBatch(ContactsContract.AUTHORITY, data);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.Exception) + " " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }

Solution

  • Contacts API

    This document is intended for programmers who want to write client applications that can interact with Google's contact lists.

    https://developers.google.com/google-apps/contacts/v3/?hl=en