![](/img/trans.png)
[英]Is it possible to add another sync account to an existing contact in android?
[英]Android - sync contact add programmatically to google account
在我的应用程序中,我需要将联系人添加到默认的谷歌帐户并同步它。
这是我的代码:
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 帐户上找不到它作为联系人或在同一帐户的其他设备上
我也尝试静态输入 google 帐户 xxxx@gmail.com 但结果将相同,添加到电话联系人但不与 google 帐户同步。
更新代码没问题,我忘了在我的设备上启用谷歌帐户同步
您的代码在我的设备(Android 4.0.4 和 4.1.2)上运行良好,在 Google 服务器上帐户的联系人会自动出现,并从一台设备到另一台设备。 顺便说一下,非常感谢您的代码。
恕我直言,问题不是代码,而是您设备的同步设置。
如果您在设备中打开了多个帐户,它只会保存在第一个帐户中,而不是默认的一个帐户中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.