【发布时间】:2015-11-20 08:06:43
【问题描述】:
在我的应用中,我需要将联系人添加到默认谷歌帐户并同步。
这是我的代码:
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()返回google账号
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 但结果会一样,添加到手机联系人但不与谷歌账户同步。
更新 代码没问题,我忘了在我的设备上启用谷歌帐户同步
【问题讨论】:
标签: android synchronization contacts google-account