How to look-up a contact's name from their phone number on Android?

后端 未结 2 1854
挽巷
挽巷 2020-12-01 06:03

I am trying to get the sender\'s name from the contacts database using a content provider.

The problem is I don\'t know how to implement it. Like now I can only pull

相关标签:
2条回答
  • 2020-12-01 06:11

    Yes, this is possible using ContactsContract.PhoneLookup.CONTENT_FILTER_URI in Android 2.0 and higher and Contacts.Phones.CONTENT_FILTER_URL in Android 1.6 and earlier.

    For example usage, see the documentation for ContactsContract.PhoneLookup. Excerpt below:

    // Android 1.6 and earlier (backwards compatible for Android 2.0+)
    Uri uri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(phoneNumber));
    
    // Android 2.0 and later
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    
    // Query the filter URI
    String[] projection = new String[]{ PhoneLookup.DISPLAY_NAME, ...
    Cursor cursor = context.getContentResolver().query(uri, projection, ...
    

    UPDATE: The format of the phone number does not matter. Comparison is robust and highly optimized on Android; it's done using a native sqlite function named PHONE_NUMBERS_EQUAL. For more details, search the codebase for this method. By the way, I'm not certain if it's safe to use that function directly in your own apps, but I wouldn't.

    0 讨论(0)
  • 2020-12-01 06:17

    Here's what I did

    ContentResolver localContentResolver = this.mContext.getContentResolver();
    Cursor contactLookupCursor =  
       localContentResolver.query(
                Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, 
                Uri.encode(phoneNumber)), 
                new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID}, 
                null, 
                null, 
                null);
    try {
    while(contactLookupCursor.moveToNext()){
        String contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
        String contactId = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
        Log.d(LOGTAG, "contactMatch name: " + contactName);
        Log.d(LOGTAG, "contactMatch id: " + contactId);
        }
    } finally {
    contactLookupCursor.close();
    } 
    

    Passing in your phone number you already have into Uri.encode(phoneNumber)

    0 讨论(0)
提交回复
热议问题