1

我在这里遇到了一些问题,因为我刚刚开始为 Android 开发。我从 Android 官方网站“ http://developer.android.com/training/contacts-provider/retrieve-names.html ”下载了示例,它基本上能够从手机中检索显示所有联系人。我想添加的功能是只显示来自某个组的联系人,例如“朋友”(硬编码)。

就我缩小范围而言,我必须更改选择部分

  final static String SELECTION =
            (Utils.hasHoneycomb() ? Contacts.DISPLAY_NAME_PRIMARY : Contacts.DISPLAY_NAME) +
            "<>''" + " AND " + Contacts.IN_VISIBLE_GROUP + "=1";

像这样

  final static String SELECTION =
            Contacts.GroupID = "Friends";

这给了我错误,因为它找不到该列。

我非常渴望探索 Android 的潜力,但那个让我很头疼。

4

1 回答 1

6

有两种方法可以获取组的联系人列表。首先,我假设您有 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);
}

请注意,在此方法的第二次获取中,我们检查accountNameaccountType以确保此记录与该组相关,因为可能有一些记录存储用于其他应用程序,例如WhatsApp。我们不喜欢得到那些。好?

我希望对你有用。

于 2014-02-23T10:52:00.457 回答