Get phone number without country code for the purpose of comparing numbers

╄→гoц情女王★ 提交于 2019-12-06 21:15:14

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/6813638/get-phone-number-without-country-code-for-the-purpose-of-comparing-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!