按电话号码搜索联系人

2024-02-19

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

我通常这样搜索联系人:

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

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

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


如果你想要完整的代码:

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按电话号码搜索联系人 的相关文章

随机推荐