android 通过电话号码来获取联系人姓名

通过电话号码来获取联系人姓名的程序如下,通过ContactsContract.PhoneLookup.CONTENT_FILTER_URI来获取对应adress(电话号码)的信息。

private String getContactName(String number) {
        if (TextUtils.isEmpty(number)) {
            return null;
        }        

        final ContentResolver resolver = mResolver.get();
        
        Uri lookupUri = null;
        String[] projection = new String[] { PhoneLookup._ID, PhoneLookup.DISPLAY_NAME };
        Cursor cursor = null;
        try {
            lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
            cursor =resolver.query(lookupUri, projection, null, null, null);
        } catch (Exception ex) {
            ex.printStackTrace();
            try {
                lookupUri = Uri.withAppendedPath(android.provider.Contacts.Phones.CONTENT_FILTER_URL,
                        Uri.encode(number));
                cursor = resolver.query(lookupUri, projection, null, null, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String ret = null;
        if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
            ret = cursor.getString(1);
        }

        cursor.close();
        return ret;
    }


你可能感兴趣的:(android 通过电话号码来获取联系人姓名)