java - 通过联系人号码获取联系人姓名在 Android 9.0 Pie 中不起作用
问题描述
我想通过以下方法从联系人列表中获取来电号码的名称。它适用于所有 android 版本,但它在 android 9.0 pie 中给出 null。
private String getContactName(String number, Context context) {
String contactName = "";
String[] projection = new String[] {
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.NUMBER,
ContactsContract.PhoneLookup.HAS_PHONE_NUMBER };
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
Cursor cursor = context.getContentResolver().query(contactUri,
projection, null, null, null);
if(cursor != null) {
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
cursor.close();
}
return contactName.equals("") ? number : contactName;
}
我也尝试了一种新方法,但它也不起作用并给我空值。我从谷歌开发者文档中得到这个代码。我的代码有什么问题,或者请帮助我了解哪种方法可以获得号码的联系人姓名。
public String onCreateIncomingConnection (String s) {
// Get the telephone number from the incoming request URI.
String phoneNumber = s;
String displayName = "Unknown caller";
boolean isCallerInWorkProfile = false;
// Look up contact details for the caller in the personal and work profiles.
Uri lookupUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = getContentResolver().query(
lookupUri,
new String[]{
ContactsContract.PhoneLookup._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.PhoneLookup.CUSTOM_RINGTONE
},
null,
null,
null);
// Use the first contact found and check if they're from the work profile.
if (cursor != null) {
try {
if (cursor.moveToFirst() == true) {
displayName = cursor.getString(1);
isCallerInWorkProfile =
ContactsContract.Contacts.isEnterpriseContactId(cursor.getLong(0));
}
} finally {
cursor.close();
}
}
// Return a configured connection object for the incoming call.
// MyConnection connection = new MyConnection();
// connection.setCallerDisplayName(displayName, TelecomManager.PRESENTATION_ALLOWED);
//
// Our app's activity uses this value to decide whether to show a work badge.
// connection.setIsCallerInWorkProfile(isCallerInWorkProfile);
// Configure the connection further ...
return displayName;
}
解决方案
推荐阅读
- apache-spark - 如何将小拼花文件合并到一个大拼花文件?
- angular - 嵌套服务中的 Angular 嵌套 observable - 如何
- hive - 在 apache hive 的维度表中具有代理键或 nk+effective_time 是否更好
- javascript - React 应用程序 - 在后台渲染提要
- kubernetes - coredns 容器在 kubernetes 工作节点中反复重启
- powershell - 如何从字符串中仅提取版本号
- linux - 仅删除文件名中至少包含一位数字的文件而不是目录
- c++ - 调用 mongocxx::instance 返回“mongoc: 无法初始化 OpenSSL”
- c# - 将东/北转换为纬度 Lng
- ruby-on-rails - Ruby on Rails 扩展 gem 的类并更改其继承类