如何从已知联系人获取群组名称

How to get group name from a known contact

我正在尝试根据字符串从联系人姓名中获取群组名称。我认为这将是一个更常见的问题,但我在 google 或此处看到的每个答案都已过时、没有答案或通过解释有关组的所有内容而错误地回答了除了实际问题所问的内容。再一次,你如何获得你已经知道联系人姓名的联系人的组名?

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()) {
    String contactname=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String contactgroup =  "GET GROUP NAME FROM STRING"(contactname);     
}

phones.close();

此方法returns给定联系人姓名的组标题列表:

public List<String> getGroupsTitle(String name, Context context) {

    List<String> groupsTitle = new ArrayList<>();

    String contactId = null;

    Cursor cursorContactId = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID},
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + "=?",
            new String[]{name},
            null);

    if (cursorContactId.moveToFirst()) {
        contactId = cursorContactId.getString(0);
    }

    cursorContactId.close();

    if (contactId == null)
        return null;

    List<String> groupIdList = new ArrayList<>();

    Cursor cursorGroupId = context.getContentResolver().query(
            ContactsContract.Data.CONTENT_URI,
            new String[]{ContactsContract.Data.DATA1},
            String.format("%s=? AND %s=?", ContactsContract.Data.CONTACT_ID, ContactsContract.Data.MIMETYPE),
            new String[]{contactId, ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE},
            null);

    while (cursorGroupId.moveToNext()) {
        String groupId = cursorGroupId.getString(0);
        groupIdList.add(groupId);
    }
    cursorGroupId.close();

    Cursor cursorGroupTitle = getContentResolver().query(
            ContactsContract.Groups.CONTENT_URI, new String[]{ContactsContract.Groups.TITLE},
            ContactsContract.Groups._ID + " IN (" + TextUtils.join(",", groupIdList) + ")",
            null,
            null);

    while (cursorGroupTitle.moveToNext()) {
        String groupName = cursorGroupTitle.getString(0);
        groupsTitle.add(groupName);
    }
    cursorGroupTitle.close();

    return groupsTitle;
}