有两种方法可以获取组的联系人列表。首先,我假设您有 GroupId 并且想要获取相关的联系人列表。
String[] projection = {
ContactsContract.Groups._ID,
ContactsContract.Groups.TITLE,
ContactsContract.Groups.ACCOUNT_NAME,
ContactsContract.Groups.ACCOUNT_TYPE
};
return context.getContentResolver().query(
ContactsContract.Groups.CONTENT_URI, projection, ContactsContract.Groups._ID + "=" + groupId , null, null
);
第二种方式:
我想您想通过常量名称获取特定组的联系人。所以,你改变上面的代码就足够了:
context.getContentResolver().query(
ContactsContract.Groups.CONTENT_URI, projection, ContactsContract.Groups.ACCOUNT_NAME + "='Friends'" , null, null
);
现在你有来自特定组的必要详细信息。然后您可以获取联系人列表列表:
public static Cursor getContactsOfGroup(Group group) {
// getting ids of contacts that are in this specific group
String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "="
+ group.id + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
Cursor query = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID
}, where, null, ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
String ids = "";
for (query.moveToFirst(); !query.isAfterLast(); query.moveToNext()) {
ids += "," + query.getString(0);
}
if (ids.length() > 0) {
ids = ids.substring(1);
}
// getting all of information of contacts. it fetches all of number from every one
String[] projection = new String[]{
"_id",
"contact_id",
"lookup",
"display_name",
"data1",
"photo_id",
"data2", // number type: 1:home, 2:mobile, 3: work, else : other
};
String selection = "mimetype ='" + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'"
+ " AND account_name='" + group.accountName + "' AND account_type='" + group.accountType + "'"
+ " AND contact_id in (" + ids + ")";
return context.getContentResolver().query(BASE_URI, projection, selection, null, null);
}
请注意,在此方法的第二次获取中,我们检查accountName和accountType以确保此记录与该组相关,因为可能有一些记录存储用于其他应用程序,例如WhatsApp。我们不喜欢得到那些。好?
我希望对你有用。