Android:从电话号码中检索联系人姓名

Android:从电话号码中检索联系人姓名

问题描述:

我想检索与传入电话号码相关联的联系人姓名.当我在广播接收器中处理传入号码时,有一个带有来电者姓名的字符串将极大地帮助我的项目.

I would like to retrieve the name of a contact associated with an incoming telephone number. As I process the incoming number in the broascastreceiver having a String with the name of the incoming caller would help my project greatly.

我认为这涉及使用 sql WHERE 子句作为过滤器的查询,但我需要对联系人进行排序吗?一个例子或提示会很有帮助.

I would think this involves a query using the sql WHERE clause as a filter, but do I need to sort the contacts? An example or hint would be of great assistance.

为此,您需要按照描述使用优化的 PhoneLookup 提供程序.

For that you need to use the optimized PhoneLookup provider as described.

AndroidManifest.xml中添加权限:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

那么:

public String getContactName(final String phoneNumber, Context context)
{
    Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));

    String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};

    String contactName="";
    Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);

    if (cursor != null) {
        if(cursor.moveToFirst()) {
            contactName=cursor.getString(0);
        }
        cursor.close();
    }

    return contactName;
}