首页 > 解决方案 > 通过联系人号码获取联系人姓名在 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;
}

标签: javaandroidlistkotlincontacts

解决方案


推荐阅读