Question

I can obtain the phone number from an incoming call or from a sms message. unfortunately, in case of the SMS there might be the country code in it. So, basically I need to obtain the plain phone number, without country code, in order to compare it with existing numbers in Contacts.

Was it helpful?

Solution

If you want to compare phone numbers you can always use the

PhoneNumberUtils.compare(number1, number2);

or

PhoneNumberUtils.compare(context, number1, number2);

Then you don't have to worry about the country code, it will just compare the numbers from the reversed order and see if they match (enough for callerID purposes at least).

OTHER TIPS

fast untested approach (AFAIK phone numbers have 10 digits):

// As I said, AFAIK phone numbers have 10 digits... (at least here in Mexico this is true)
int digits = 10;
// the char + is always at first.
int plus_sign_pos = 0;

// Always send the number to this function to remove the first n digits (+1,+52, +520, etc)
private String removeCountryCode(String number) {
    if (hasCountryCode(number)) {
        // +52 for MEX +526441122345, 13-10 = 3, so we need to remove 3 characters
        int country_digits = number.length() - digits;
        number = number.substring(country_digits);
    }
    return number;
}

// Every country code starts with + right?
private boolean hasCountryCode(String number) {
    return number.charAt(plus_sign_pos) == '+'; // Didn't String had contains() method?...
}

then you just call these functions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top