Android 通过电话号码搜索联系人

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3712112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:29:37  来源:igfitidea点击:

Search contact by phone number

androidandroid-contacts

提问by Tiago Costa

In my app, user writes a phone number, and I want to find the contact name with that phone number?

在我的应用程序中,用户写了一个电话号码,我想找到该电话号码的联系人姓名?

I usually search the contacts like this:

我通常这样搜索联系人:

Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

But I do this to access all contacts... In this app I only want to get the contact name of the given phone number... How can I restrict the query?

但我这样做是为了访问所有联系人...在这个应用程序中,我只想获取给定电话号码的联系人姓名...如何限制查询?

Or do I have to go trough all contacts and see if any has the given phone number? But I believe that this can be very slow this way...

还是我必须通过所有联系人查看是否有给定的电话号码?但我相信这样会很慢......

回答by Felipe

If you want the complete code:

如果你想要完整的代码:

public String getContactDisplayNameByNumber(String number) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    String name = "?";

    ContentResolver contentResolver = getContentResolver();
    Cursor contactLookup = contentResolver.query(uri, new String[] {BaseColumns._ID,
            ContactsContract.PhoneLookup.DISPLAY_NAME }, null, null, null);

    try {
        if (contactLookup != null && contactLookup.getCount() > 0) {
            contactLookup.moveToNext();
            name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
            //String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
        }
    } finally {
        if (contactLookup != null) {
            contactLookup.close();
        }
    }

    return name;
}

回答by Pentium10

You should have a look at the recommended ContactsContract.PhoneLookupprovider

你应该看看推荐的ContactsContract.PhoneLookupprovider

A table that represents the result of looking up a phone number, for example for caller ID. To perform a lookup you must append the number you want to find to CONTENT_FILTER_URI. This query is highly optimized.

表示查找电话号码的结果的表格,例如来电显示。要执行查找,您必须将要查找的数字附加到 CONTENT_FILTER_URI。这个查询是高度优化的。

Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,...