📜 ⬆️ ⬇️

Search for a contact by phone number

In one of the applications there was a question of finding a contact by phone number (when receiving SMS). The task was not so simple - in the contact database, phones are often written in an arbitrary (user-friendly) format: here you can use 8 instead of the country code, and brackets and / or spaces to separate the parts of the number. And then the operator added his own creative and converted the author’s number to a more readable format — the country code, the operator code, and the phone number itself, separated by spaces. Its function of bringing numbers to the international format did not cope in good faith, and it took too much time. Searching the answer in the documentation did not give any special results either, but the study of the sources helped. It turned out that in SQLite queries you can use the PHONE_NUMBERS_EQUAL (NUMBER1, NUMBER2, STRICT) function. The third parameter can be omitted. This method works fine.
String[] projection = new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.Contacts.LOOKUP_KEY, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.STARRED, ContactsContract.Contacts.CONTACT_STATUS, ContactsContract.Contacts.CONTACT_PRESENCE }; String selection = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"; String selectionArgs = new String[] { phoneNumber }; Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, selection, selectionArgs, null); 
It is desirable to bring the source number itself into a simpler look before the search:
 String phoneNumber = PhoneNumberUtils.stripSeparators(sourcePhoneNumber); 
Maybe someone will help and save time and effort.

')

Source: https://habr.com/ru/post/154361/


All Articles