سؤال

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.

هل كانت مفيدة؟

المحلول

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).

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top