Android(Java)-通过电子邮件查找联系人并预览(如果存在)

时间:2019-01-23 18:49:01

标签: java android

现在,我们有了一个应用程序,在该应用程序中(经过许可)我们可以查找联系人,如果存在,则显示其联系人卡片。但是查找似乎效率很低,它遍历每个人,似乎不正确。是否有更好的查询联系人数据库来仅查找具有我们所需电子邮件地址的联系人?

下面的当前代码(无效):

public static void showCardIfPossible(String email, Context context) {
        Long contactId = lookupByEmail(email, context);
        if (contactId != null) {
            viewCardFor(context, contactId);
        }
    }

    public static Long lookupByEmail(String email, Context context) {

        Long contactId = null;

        ContentResolver cr = context.getContentResolver();
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if (cursor == null || cursor.getCount() == 0) {
            return null;
        }

        while (cursor.moveToNext())
        {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor cur1 = cr.query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                    new String[]{id}, null);

            if (cur1 != null && cur1.getCount() > 0) {
                while (cur1.moveToNext()) {
                    //to get the contact names
                    String contactName=cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String contactEmail = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    if(email.equals(contactEmail) || email.equals(contactName)){
                        contactId = Long.valueOf(id);
                    }
                }
                cur1.close();
            }
        }
        cursor.close();

        return contactId;
    }

    public static void viewCardFor(Context context, long contactId) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
        intent.setData(uri);
        context.startActivity(intent);
    }

1 个答案:

答案 0 :(得分:1)

是的,您可以直接在Email.CONTENT_URI上进行查询,然后使用选择来找到合适的联系人:

public static Long lookupByEmail(String email, Context context) {

    ContentResolver cr = context.getContentResolver();
    Long contactId = null;

    String[] projection = new String[] { Email.CONTACT_ID };
    String selection = Email.ADDRESS + "='" + email + "'";
    Cursor cur = cr.query(Email.CONTENT_URI, projection, selection, null, null);

    if (cur != null) {
       if (cur.moveToFirst()) {
          contactId = cur.getLong(0);      
       }
       cur.close();
    }

    return contactId;
}