getting detail country name and country code of a given phone number

6.2k views Asked by At

I able to detect incoming calls in android but problem is that I want to know to the country code of that phone number so that I can analyze whether it is a national or international number. I know about libphonenumber but It needs to know region code before hand to get the country code as shown in the example

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}

it already knows to put "CH" as a parameter. but we don't know if the number is to known to us then how we can analyze that number.

1

There are 1 answers

2
Willi Mentzel On

As long as it is not a regional number (in which case it is just a plain number and no lib in this world could determine where it is from) you can specify "ZZ" or null for the second parameter of parse.

This is what the documentation says:

region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.

After you where able to create an instace of PhoneNumber you can simply call getRegionCodeForNumber as shown below.

String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
   PhoneNumber numberProto = phoneUtil.parse(swissNumberStr, "ZZ");
   System.out.println(phoneUtil.getRegionCodeForNumber(numberProto));
} catch (NumberParseException e) {
   System.err.println("NumberParseException was thrown: " + e.toString());
}