首页 > 解决方案 > 如何使用phoneNumber或电子邮件ID作为android中的参数从通讯录中获取联系人姓名

问题描述

我正在寻找一种将电话号码或电子邮件 ID 作为参数并给出保存在 android 电话联系人中的关联联系人姓名的方法。

下面的代码用于获取通过手机号码的联系人姓名,但我需要为电子邮件 ID 和电话号码提供一种方法,这样当我们通过电话号码或电子邮件时,如果返回联系人姓名。所以下面的代码只给出电话号码关联的联系人姓名,其中电子邮件 ID 名称未返回。

下面是代码:

 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();

                    if (contactName == null) {
                        return name;
                    }
                    if (contactName.isEmpty()) {
                        return name;
                    }
                }
 return name;

任何帮助表示赞赏

标签: android

解决方案


Below method will help in getting contact name when using phone number or email id
  public static String fetchContactNameFromContacts(Context context, final String phoneOrEmail) {
        String name = phoneOrEmail;
        Uri uri;
        try {
            if (ContextCompat.checkSelfPermission(context, READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "permission granted");
                String contactName = "";
                if(isValidMobile(phoneOrEmail)) {
                    Log.d(TAG, "its phone number");
                    uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneOrEmail));
                }else {
                    Log.d(TAG, "its email id");
                    uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phoneOrEmail));

                }
                String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};
                Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);

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

                    if (contactName == null) {
                        return name;
                    }
                    if (contactName.isEmpty()) {
                        return name;
                    }
                }

            }
        } catch (Exception e) {
           
        }
        return name;
    }

推荐阅读