首页 文章

Android - 同步联系人以编程方式添加到Google帐户

提问于
浏览
3

在我的应用程序中,我需要添加联系人到默认谷歌帐户并同步它 .

这是我的代码:

public static void addContact(Context context, String DisplayName,String WorkNumber, String MobileNumber, String emailID,
                                     String jobTitle, String company, String address){


    ArrayList <ContentProviderOperation> ops = new ArrayList < ContentProviderOperation > ();
    String account = getUsernameLong(context);

    ops.add(ContentProviderOperation.newInsert(
            ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.google")
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, account)

            .build());

    //------------------------------------------------------ Names
    if (DisplayName != null) {
        ops.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,
                        DisplayName).build());
    }

    ..................

    try {
        context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        //requestSyncNow(context);
    } catch (Exception e) {
        e.printStackTrace();

                try {
                    //Toast.makeText(context, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                } catch (Exception e1) {

                }
    }


}

这里函数getUsernameLong()返回谷歌帐户

public static String getUsernameLong(Context context) {
                AccountManager manager = AccountManager.get(context);
                Account[] accounts = manager.getAccountsByType("com.google");
                List<String> possibleEmails = new LinkedList<String>();

                for (Account account : accounts) {

                    // account.name as an email address only for certain account.type values.
                    possibleEmails.add(account.name);
                    Log.i("DGEN ACCOUNT","CALENDAR LIST ACCOUNT/"+account.name);
                }

                if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
                    String email = possibleEmails.get(0);
                    return email;

                }
                return null;
            }

此代码为联系人添加名称,在手机上我可以看到手机上的xxx@gmail.com帐户,但它与远程帐户不同步 . 我无法在gmail帐户上找到它作为联系人或在同一帐户的其他设备上找到它

我也尝试输入静态谷歌帐户xxxx@gmail.com但结果将是相同的,添加到手机联系但不与谷歌帐户同步 .

UPDATE 代码没问题,我忘了在我的设备上启用Google帐户同步

2 回答

  • 0

    您的代码在我的设备上运行正常(Android 4.0.4和4.1.2),在Google服务器上的帐户联系人会自动显示,并从一个设备显示到其他设备 . 顺便说一下,非常感谢你的代码 .

    恕我直言,问题不是代码,而是设备的同步设置 .

  • 1

    如果您在设备中打开了多个帐户,则只保存在第一个帐户而不是默认帐户中 .

相关问题