Get phone number without country code in Android

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

+8
android phone-number mobile-country-code
source share
2 answers

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

PhoneNumberUtils.compare(number1, number2); 

or

 PhoneNumberUtils.compare(context, number1, number2); 

Then you don’t need to worry about the country code, it will simply compare the numbers with the reverse order and see if they match (enough for callerID purposes, at least).

+27
source share

quick unverified 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

-one
source share

All Articles