1

Is there any way to find the country code from my mobile number. Basically, I am working for a chat application I need to find the country code by using the mobile number. Is it possible?

For example:

My Country - India,
Country Code - +91,
My number - 9787248566

Now I have only my number . I don't know the country code. I don't know which country it is. Is it possible to achieve this in Android programmatically?

Amsheer
  • 7,046
  • 8
  • 47
  • 81

2 Answers2

3

If you already have complete mobile number in a specific format e.g. +91-99xxxxxxxx and want to fetch country code = IN, then here is a reference to a solution.

Use a lib in your gradle.

//Phone Utils lib.
implementation 'com.googlecode.libphonenumber:libphonenumber:7.0'

And the code which will help to find the country code and other information is as below.

PhoneNumberUtil utils = PhoneNumberUtil.getInstance();
try {
    for (String region : utils.getSupportedRegions()) {
        // Check whether it's a valid number.
        boolean isValid = utils.isPossibleNumber(mobileNo, region);
        if (isValid) {
            Phonenumber.PhoneNumber number = util.parse(mobileNo, region);
            // Check whether it's a valid number for the given region.
            isValid = utils.isValidNumberForRegion(number, region);
            if (isValid) {
                Log.d("Region:" , region); // IN
                Log.d("Phone Code", number.getCountryCode()); // 91
                Log.d("Phone No.", number.getNationalNumber()); // 99xxxxxxxxxx  
            }
        }
    }
} catch (NumberParseException e) {
    e.printStackTrace();
}
Harpreet
  • 2,990
  • 3
  • 38
  • 52
  • What if we get multiple country code support for same number inside loop how we can handle it here with this code ? – Jay Rathod Jul 07 '23 at 08:08
2

Use TelephonyManager.getSimCountryIso().

If you want to map that to the number, see how to get country phone prefix from iso

Community
  • 1
  • 1
F43nd1r
  • 7,690
  • 3
  • 24
  • 62