android - 如何使用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;
任何帮助表示赞赏
解决方案
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;
}
推荐阅读
- mysql - SQL:计算行间差异的平均值
- python - 将文件从文件夹复制到不同文件夹时出现问题
- c# - 应用程序在配置调试中抛出异常但在发布中工作
- python - 如何以比使用 python 进行 Windows 搜索更快的方式搜索文件?
- sql-server - SQL Server:编辑查询结果在 SQL Server 发送的电子邮件中的显示方式
- sql - MSSQL - 如何根据准备日期汇总数量以输入散点图?
- angular - 如果值匹配,如何检查角度材料复选框
- javascript - UTF8 从 PHP 到 JS 警报
- php - 如何在 xpath 和 DOM 操作 (PHP) 之后检索生成的 DOM 标记字符串?
- java - 带有netty“反射setAccessible(true)禁用”的spring-web-flux错误