2

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

quealegriamasalegre
  • 2,887
  • 1
  • 13
  • 35
  • I think Google already provides the following library and in some OS, some system apps might be using that? https://github.com/google/libphonenumber – Reaz Murshed Mar 23 '20 at 03:41
  • @Reaz I also had a look at it as well as this answer https://stackoverflow.com/a/48873912/10637400 but I could not find a method to get the country code in libphonenumber itself but rather in the mentioned forked library by MichaelRocks. I mean It does solve my problem but is this also the way the contacts app is doing it?? I mean kudos to Michael but he doesnt work for google (i guess) and I would have to trust him maintaining his own database and not having any omisions or mistakes in his databases. it just seems to me like somethig there should be an official library for – quealegriamasalegre Mar 23 '20 at 03:55

1 Answers1

2

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);
marmor
  • 27,641
  • 11
  • 107
  • 150