Search code examples
androidandroid-contactstelephonymanager

How does my phone (and some apps) know what country code prefix (like +1, +505, +49...) to append to numbers in my contacts


I was recently amazed that there doesnt seem to be a standard method in android to get the country code (and I mean +1,+49,+39 and not US,GE,IT) of your own phone. TelephonyManager lets you get a bunch of other information including the two letter string country code of your phone (IN, US, IT...) or even your sim but not the dialling prefix.

after extensively googling this issue I found that people have solved this by creating their own databases of country_code-prefix correspondences (i.e. {IT,+39}...) (see this) which sounds crazy (and feels like rubbing two sticks together to make fire XD) and would mean countless developers are writing each their own database allover the world to solve an issue TelephonyManager should be solving.

I find it weird that some of the system apps seem to know this code from somewhere. I am, for instance, able to call contacts from abroad even if I saved their number without the prefix and whatsapp is also usually able to infer the right prefix.

what method is my contacts app using to infer the right prefix? does it have its own private database that it wont share with us? is there a reason for this, like some security concern Im not aware of? how does Whatsapp do it?

I am really intrigued by this. maybe I havnt googled it enough and there is method out there but many people seem to be solving it with the aforementioned database approach.

any help understanding this would be greatly appreciated


Solution

  • This is supported by Google's libphonenumber library, see https://github.com/google/libphonenumber/blob/master/java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java#L2373

    Basically you would do something like this:

    // get region, e.g. "US"
    TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String region = telephony.getNetworkCountryIso().toUpperCase(Locale.getDefault());
    
    // get country code from region, e.g. "US" => 1
    PhoneNumberUtil libphone = PhoneNumberUtil.createInstance(this);
    int code = libphone.getCountryCodeForRegion(region);