看起来Android中可能有多个联系人帐户,系统的联系人应用程序可能只显示感兴趣的帐户。因此,一种正确的方法是获取默认帐户名称和类型。
这是一个获取默认帐户名称和类型的函数:
private String[] getDefaultAccountNameAndType() {
String accountType = "";
String accountName = "";
long rawContactId = 0;
Uri rawContactUri = null;
ContentProviderResult[] results = null;
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI).withValue(RawContacts.ACCOUNT_NAME, null).withValue(RawContacts.ACCOUNT_TYPE, null).build());
try {
results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch(Exception e) {
e.printStackTrace();
} finally {
ops.clear();
}
for (ContentProviderResult result : results) {
rawContactUri = result.uri;
rawContactId = ContentUris.parseId(rawContactUri);
}
Cursor c = getContentResolver().query(
RawContacts.CONTENT_URI
, new String[] {RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_NAME}
, RawContacts._ID+"=?"
, new String[] {String.valueOf(rawContactId)}
, null);
if(c.moveToFirst()) {
if(!c.isAfterLast()) {
accountType = c.getString(c.getColumnIndex(RawContacts.ACCOUNT_TYPE));
accountName = c.getString(c.getColumnIndex(RawContacts.ACCOUNT_NAME));
}
}
getContentResolver().delete(rawContactUri, null, null);
c.close();
c = null;
return new String[] { accountName, accountType };
}
然后我们可以在创建新组时设置它们:
String accountNameType[] = getDefaultAccountNameAndType();
ArrayList<ContentProviderOperation> o = new ArrayList<ContentProviderOperation>();
o.add(ContentProviderOperation.newInsert(Groups.CONTENT_URI)
.withValue(Groups.TITLE, groupTitle)
.withValue(Groups.GROUP_VISIBLE, true)
.withValue(Groups.ACCOUNT_NAME, accountNameType[0])
.withValue(Groups.ACCOUNT_TYPE, accountNameType[1])
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, o);
} catch (Exception e) {
Log.e("ContactsManager", "Failed to create new contact group: "+e);
return;
}