Search code examples
androidbroadcastreceiverphonenumberutils

Difference of Contact No. Format


I'm developing an sms blocker for which I need to save contact numbers in DB and compare them to SMS sender. I've only default SMS application installed on my android phone. But there is difference of contact number format as picked from following code:

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT);

and when I receive SMS using broadcast receiver (see following code segment):

SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String number = phoneNumber;
String message = currentMessage.getDisplayMessageBody();

The format of phone # in my contact list is like "033-xxxx-xxxx" without country code but SMS Broadcast Receiver adds country code to the number like "+92331xxxxxxx".

My question (a) is why SMS receiver is using different format then that is saved in my contact lists and (b) how do I compare these numbers in my SMS broadcast receiver.


Solution

  • Check out PhoneNumberUtils.You need to let the O/S help you because it can be international number.

    Use String incomingNumber = PhoneNumberUtils.formatNumber(incomingNumber,defaultCountryIso);

    on both numbers, then compare them.
    To compare you do this:

       boolean SameNumber= PhoneNumberUtils.compare(phoneNumber, otherPhoneNumber)
    //if true, numbers are the same