查询指定组中的联系成员?

时间:2012-01-26 19:02:06

标签: android android-contentprovider android-contacts

我需要获取Android联系人中特定群组的成员。

我有联系人组名称及其ID

任何人都可以向我提供如何查询联系人提供商以查找特定群组中的成员吗?

1 个答案:

答案 0 :(得分:4)

试试这个方法:

private Cursor getContacts(String groupID) {
   Uri uri = ContactsContract.Data.CONTENT_URI;

   String[] projection = new String[] {
       ContactsContract.Contacts._ID,
       ContactsContract.Data.CONTACT_ID,
       ContactsContract.Data.DISPLAY_NAME
   };

   String selection = null;
   String[] selectionArgs = null;

   if(groupID != null && !"".equals(groupID)) {
       selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID
                   + " = ?";
       selectionArgs = new String[] { groupID };
   }
   else
       selection = "1) GROUP BY (" + ContactsContract.Data.CONTACT_ID;

       String sortOrder = ContactsContract.Contacts.DISPLAY_NAME 
                          + " COLLATE LOCALIZED ASC ";

       return getContentResolver().query(uri, projection, 
                                         selection, selectionArgs, sortOrder);
}

适用于Android 2.3.3及更低版本,但不适用于Android 4+,我目前不知道原因。

<强> UPD。

在Android 4+中拒绝向SQL查询添加自定义字符串参数“GROUP BY”,因此我已经建立了此解决方法:

private Cursor getContacts(String groupID) {
    Uri uri = ContactsContract.Data.CONTENT_URI;

    String[] projection = new String[] {
            ContactsContract.Contacts._ID,
            ContactsContract.Data.CONTACT_ID,
            ContactsContract.Data.DISPLAY_NAME
    };

    String selection = null;
    String[] selectionArgs = null;

    if(groupID != null && !"".equals(groupID)) {
        selection = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID 
                        + " = ?";
        selectionArgs = new String[] { groupID };
    }

    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME 
                        + " COLLATE LOCALIZED ASC ";

    Cursor cursor = getContentResolver().query(uri, projection, 
                                          selection, selectionArgs, sortOrder); 

    MatrixCursor result = new MatrixCursor(projection);
    Set<Long> seen = new HashSet<Long>();
    while (cursor.moveToNext()) {
        long raw = cursor.getLong(1);
        if (!seen.contains(raw)) {
            seen.add(raw);
            result.addRow(new Object[] { cursor.getLong(0), 
                             cursor.getLong(1), cursor.getString(2) });
        }
    }

    return result;