javaandroidphone-numberlibphonenumbermobile-country-code

Predict/Identify country codes for phone numbers


I have list of mobile phone numbers from different countries from Android contacts. Some of these contacts have country codes while some of them don't.

So, a solution could be:

  1. Get all supported country codes of the world
  2. Loop a number with all the country codes
  3. Check validity of number

This could be one way to predict a number for supported countries. I am wondering if there is a better way to approach this problem?


Solution

  • PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    
    String numberStr = "04157012311";
    Set<String> allRegions = phoneUtil.getSupportedRegions();
    Set<String> validRegions = new LinkedHashSet<String>();
    
    for (String region : allRegions) {
      try {
        if (phoneUtil.isValid(phoneUtil.parse(numberStr, region))) {
          validRegions.add(region);
        }        
      } catch (NumberParseException e) {
        // Handle NumberParseException
      }
    }
    

    validRegions will contain ISO codes of regions where your phone number can be located