3
在我的應用程序中,我需要將聯繫人添加到默認的Google帳戶並進行同步。Android - 同步聯繫人以編程方式添加到Google帳戶
這裏我的代碼:
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;
}
該代碼添加聯繫人姓名和手機上,我可以看到,它在手機上[email protected]帳戶,但它不與遠程帳戶同步。我無法在Gmail帳戶上找到它作爲聯繫人或其他設備上的同一個帳戶
我也嘗試輸入靜態谷歌帳戶[email protected]但結果將是相同的,添加到手機聯繫人但不同步谷歌帳戶。
UPDATE 代碼就OK了,我忘了讓谷歌帳戶的同步設備上
謝謝,這是我的設備同步問題。謝謝。 – drd