-
public class PhoneNumberUtilUtility for international phone numbers. Functionality includes formatting, parsing and validation.
If you use this library, and want to be notified about important changes, please sign up to our mailing list. NOTE: A lot of methods in this class require Region Code strings. These must be provided using CLDR two-letter region-code format. These should be in upper-case. The list of the codes can be found here: http://www.unicode.org/cldr/charts/30/supplemental/territory_information.html
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public enumPhoneNumberUtil.PhoneNumberFormatINTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T RecommendationE.123. However we follow local conventions such as using '-' instead of whitespace asseparators. For example, the number of the Google Switzerland office will be written as"+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format. E164format is as per INTERNATIONAL format but with no formatting applied, e.g. "+41446681800".RFC3966 is as per INTERNATIONAL format, but with all spaces and other separating symbolsreplaced with a hyphen, and with any phone number extension appended with ";ext=". It alsowill have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800".Note: If you are considering storing the number in a neutral format, you are highly advised touse the PhoneNumber class.
public enumPhoneNumberUtil.PhoneNumberTypeType of phone numbers.
public enumPhoneNumberUtil.MatchTypeTypes of phone number matches. See detailed description beside the isNumberMatch() method.
public enumPhoneNumberUtil.ValidationResultPossible outcomes when testing if a PhoneNumber is possible.
public enumPhoneNumberUtil.LeniencyLeniency when finding potential phone numbers in textsegments. The levels here are ordered in increasing strictness.
-
Field Summary
Fields Modifier and Type Field Description public final static StringREGION_CODE_FOR_NON_GEO_ENTITYprivate volatile ShortNumberInfoshortNumberInfoprivate final Set<String>supportedRegions
-
Method Summary
Modifier and Type Method Description ShortNumberInfogetShortNumberInfo()Set<String>getSupportedRegions()Returns all regions the library has metadata for. static StringnormalizeDigitsOnly(CharSequence number)Normalizes a string of characters representing a phone number. static StringnormalizeDiallableCharsOnly(CharSequence number)Normalizes a string of characters representing a phone number. static StringconvertAlphaCharactersInNumber(CharSequence number)Converts all alpha characters in a number to their respective digits on a keypad, but retainsexisting formatting. intgetLengthOfGeographicalAreaCode(Phonenumber.PhoneNumber number)Gets the length of the geographical area code from thePhoneNumber object passed in, so that clients could use itto split a national significant number into geographical area code and subscriber number. intgetLengthOfNationalDestinationCode(Phonenumber.PhoneNumber number)Gets the length of the national destination code (NDC) from thePhoneNumber object passed in, so that clients could use itto split a national significant number into NDC and subscriber number. static StringgetCountryMobileToken(int countryCallingCode)Returns the mobile token for the provided country calling code if it has one, otherwisereturns an empty string. Set<Integer>getSupportedGlobalNetworkCallingCodes()Returns all global network calling codes the library has metadata for. Set<Integer>getSupportedCallingCodes()Returns all country calling codes the library has metadata for, covering both non-geographicalentities (global network calling codes) and those used for geographical entities. Set<PhoneNumberUtil.PhoneNumberType>getSupportedTypesForRegion(String regionCode)Returns the types for a given region which the library has metadata for. Set<PhoneNumberUtil.PhoneNumberType>getSupportedTypesForNonGeoEntity(int countryCallingCode)Returns the types for a country-code belonging to a non-geographical entity which the libraryhas metadata for. static PhoneNumberUtilcreateInstance(MetadataLoader metadataLoader)Create a new PhoneNumberUtil instance to carry out international phone numberformatting, parsing, or validation. static PhoneNumberUtilcreateInstance(Context context)Create a new PhoneNumberUtil instance to carry out international phone numberformatting, parsing, or validation. booleanisNumberGeographical(Phonenumber.PhoneNumber phoneNumber)Tests whether a phone number has a geographical association. booleanisNumberGeographical(PhoneNumberUtil.PhoneNumberType phoneNumberType, int countryCallingCode)Overload of isNumberGeographical(PhoneNumber), since calculating the phone number type isexpensive; if we have already done this, we don't want to do it again. Stringformat(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat)Formats a phone number in the specified format using default rules. voidformat(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, StringBuilder formattedNumber)Same as format, but accepts a mutable StringBuilder asa parameter to decrease object creation when invoked many times. StringformatByPattern(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, List<Phonemetadata.NumberFormat> userDefinedFormats)Formats a phone number in the specified format using client-defined formatting rules. StringformatNationalNumberWithCarrierCode(Phonenumber.PhoneNumber number, CharSequence carrierCode)Formats a phone number in national format for dialing using the carrier as specified in the {@code carrierCode}.StringformatNationalNumberWithPreferredCarrierCode(Phonenumber.PhoneNumber number, CharSequence fallbackCarrierCode)Formats a phone number in national format for dialing using the carrier as specified in thepreferredDomesticCarrierCode field of the PhoneNumber object passed in. StringformatNumberForMobileDialing(Phonenumber.PhoneNumber number, String regionCallingFrom, boolean withFormatting)Returns a number formatted in such a way that it can be dialed from a mobile phone in aspecific region. StringformatOutOfCountryCallingNumber(Phonenumber.PhoneNumber number, String regionCallingFrom)Formats a phone number for out-of-country dialing purposes. StringformatInOriginalFormat(Phonenumber.PhoneNumber number, String regionCallingFrom)Formats a phone number using the original phone number format (e.g. StringformatOutOfCountryKeepingAlphaChars(Phonenumber.PhoneNumber number, String regionCallingFrom)Formats a phone number for out-of-country dialing purposes.Note that in this version, if the number was entered originally using alpha characters andthis version of the number is stored in raw_input, this representation of the number will beused rather than the digit representation. StringgetNationalSignificantNumber(Phonenumber.PhoneNumber number)Gets the national significant number of a phone number. Phonenumber.PhoneNumbergetExampleNumber(String regionCode)Gets a valid number for the specified region. Phonenumber.PhoneNumbergetInvalidExampleNumber(String regionCode)Gets an invalid number for the specified region. Phonenumber.PhoneNumbergetExampleNumberForType(String regionCode, PhoneNumberUtil.PhoneNumberType type)Gets a valid number for the specified region and number type. Phonenumber.PhoneNumbergetExampleNumberForType(PhoneNumberUtil.PhoneNumberType type)Gets a valid number for the specified number type (it may belong to any country). Phonenumber.PhoneNumbergetExampleNumberForNonGeoEntity(int countryCallingCode)Gets a valid number for the specified country calling code for a non-geographical entity. PhoneNumberUtil.PhoneNumberTypegetNumberType(Phonenumber.PhoneNumber number)Gets the type of a valid phone number. booleanisValidNumber(Phonenumber.PhoneNumber number)Tests whether a phone number matches a valid pattern. booleanisValidNumberForRegion(Phonenumber.PhoneNumber number, String regionCode)Tests whether a phone number is valid for a certain region. StringgetRegionCodeForNumber(Phonenumber.PhoneNumber number)Returns the region where a phone number is from. StringgetRegionCodeForCountryCode(int countryCallingCode)Returns the region code that matches the specific country calling code. List<String>getRegionCodesForCountryCode(int countryCallingCode)Returns a list with the region codes that match the specific country calling code. intgetCountryCodeForRegion(String regionCode)Returns the country calling code for a specific region. StringgetNddPrefixForRegion(String regionCode, boolean stripNonDigits)Returns the national dialling prefix for a specific region. booleanisNANPACountry(String regionCode)Checks if this is a region under the North American Numbering Plan Administration (NANPA). booleanisAlphaNumber(CharSequence number)Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. booleanisPossibleNumber(Phonenumber.PhoneNumber number)Convenience wrapper around isPossibleNumberWithReason. booleanisPossibleNumberForType(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberType type)Convenience wrapper around isPossibleNumberForTypeWithReason. PhoneNumberUtil.ValidationResultisPossibleNumberWithReason(Phonenumber.PhoneNumber number)Check whether a phone number is a possible number. PhoneNumberUtil.ValidationResultisPossibleNumberForTypeWithReason(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberType type)Check whether a phone number is a possible number of a particular type. booleanisPossibleNumber(CharSequence number, String regionDialingFrom)Check whether a phone number is a possible number given a number in the form of a string, andthe region where the number could be dialed from. booleantruncateTooLongNumber(Phonenumber.PhoneNumber number)Attempts to extract a valid number from a phone number that is too long to be valid, and resetsthe PhoneNumber object passed in to that valid version. AsYouTypeFormattergetAsYouTypeFormatter(String regionCode)Gets an io.michaelrocks.libphonenumber.android.AsYouTypeFormatter for the specific region. Phonenumber.PhoneNumberparse(CharSequence numberToParse, String defaultRegion)Parses a string and returns it as a phone number in proto buffer format. voidparse(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber)Same as parse, but accepts mutable PhoneNumber as aparameter to decrease object creation when invoked many times. Phonenumber.PhoneNumberparseAndKeepRawInput(CharSequence numberToParse, String defaultRegion)Parses a string and returns it in proto buffer format. voidparseAndKeepRawInput(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber)Same asparseAndKeepRawInput, but accepts a mutablePhoneNumber as a parameter to decrease object creation when invoked many times. Iterable<PhoneNumberMatch>findNumbers(CharSequence text, String defaultRegion)Returns an iterable over all PhoneNumberMatches in {@code text}.Iterable<PhoneNumberMatch>findNumbers(CharSequence text, String defaultRegion, PhoneNumberUtil.Leniency leniency, long maxTries)Returns an iterable over all PhoneNumberMatches in {@code text}.PhoneNumberUtil.MatchTypeisNumberMatch(Phonenumber.PhoneNumber firstNumberIn, Phonenumber.PhoneNumber secondNumberIn)Takes two phone numbers and compares them for equality. PhoneNumberUtil.MatchTypeisNumberMatch(CharSequence firstNumber, CharSequence secondNumber)Takes two phone numbers as strings and compares them for equality. PhoneNumberUtil.MatchTypeisNumberMatch(Phonenumber.PhoneNumber firstNumber, CharSequence secondNumber)Takes two phone numbers and compares them for equality. booleancanBeInternationallyDialled(Phonenumber.PhoneNumber number)Returns true if the number can be dialled from outside the region, or unknown. booleanisMobileNumberPortableRegion(String regionCode)Returns true if the supplied region supports mobile number portability. -
-
Method Detail
-
getShortNumberInfo
ShortNumberInfo getShortNumberInfo()
-
getSupportedRegions
Set<String> getSupportedRegions()
Returns all regions the library has metadata for.
-
normalizeDigitsOnly
static String normalizeDigitsOnly(CharSequence number)
Normalizes a string of characters representing a phone number. This converts wide-ascii andarabic-indic numerals to European numerals, and strips punctuation and alpha characters.
- Parameters:
number- a string of characters representing a phone number
-
normalizeDiallableCharsOnly
static String normalizeDiallableCharsOnly(CharSequence number)
Normalizes a string of characters representing a phone number. This strips all characters whichare not diallable on a mobile phone keypad (including all non-ASCII digits).
- Parameters:
number- a string of characters representing a phone number
-
convertAlphaCharactersInNumber
static String convertAlphaCharactersInNumber(CharSequence number)
Converts all alpha characters in a number to their respective digits on a keypad, but retainsexisting formatting.
-
getLengthOfGeographicalAreaCode
int getLengthOfGeographicalAreaCode(Phonenumber.PhoneNumber number)
Gets the length of the geographical area code from thePhoneNumber object passed in, so that clients could use itto split a national significant number into geographical area code and subscriber number. Itworks in such a way that the resultant subscriber number should be diallable, at least on somedevices. An example of how this could be used:
N.B.: area code is a very ambiguous concept, so the I18N team generally recommends againstusing it for most purposes, but recommends using the more general{@code * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); * PhoneNumber number = phoneUtil.parse("16502530000", "US"); * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number); * String areaCode; * String subscriberNumber; * * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number); * if (areaCodeLength > 0) { * areaCode = nationalSignificantNumber.substring(0, areaCodeLength); * subscriberNumber = nationalSignificantNumber.substring(areaCodeLength); * } else { * areaCode = ""; * subscriberNumber = nationalSignificantNumber; * } * }{@code national_number}instead. Read the following carefully before deciding to use this method:- geographical area codes change over time, and this method honors those changes;therefore, it doesn't guarantee the stability of the result it produces.
- subscriber numbers may not be diallable from all devices (notably mobile devices, whichtypically requires the full national_number to be dialled in most regions).
- most non-geographical numbers have no area codes, including numbers from non-geographicalentities
- some geographical numbers have no area codes.
- Parameters:
number- the PhoneNumber object for which clientswant to know the length of the area code
-
getLengthOfNationalDestinationCode
int getLengthOfNationalDestinationCode(Phonenumber.PhoneNumber number)
Gets the length of the national destination code (NDC) from thePhoneNumber object passed in, so that clients could use itto split a national significant number into NDC and subscriber number. The NDC of a phonenumber is normally the first group of digit(s) right after the country calling code when thenumber is formatted in the international format, if there is a subscriber number part thatfollows.N.B.: similar to an area code, not all numbers have an NDC!An example of how this could be used:
Refer to the unittests to see the difference between this function and getLengthOfGeographicalAreaCode.{@code * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); * PhoneNumber number = phoneUtil.parse("18002530000", "US"); * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number); * String nationalDestinationCode; * String subscriberNumber; * * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number); * if (nationalDestinationCodeLength > 0) { * nationalDestinationCode = nationalSignificantNumber.substring(0, * nationalDestinationCodeLength); * subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength); * } else { * nationalDestinationCode = ""; * subscriberNumber = nationalSignificantNumber; * } * }- Parameters:
number- the PhoneNumber object for which clientswant to know the length of the NDC
-
getCountryMobileToken
static String getCountryMobileToken(int countryCallingCode)
Returns the mobile token for the provided country calling code if it has one, otherwisereturns an empty string. A mobile token is a number inserted before the area code when dialinga mobile number from that country from abroad.
- Parameters:
countryCallingCode- the country calling code for which we want the mobile token
-
getSupportedGlobalNetworkCallingCodes
Set<Integer> getSupportedGlobalNetworkCallingCodes()
Returns all global network calling codes the library has metadata for.
-
getSupportedCallingCodes
Set<Integer> getSupportedCallingCodes()
Returns all country calling codes the library has metadata for, covering both non-geographicalentities (global network calling codes) and those used for geographical entities. This could beused to populate a drop-down box of country calling codes for a phone-number widget, forinstance.
-
getSupportedTypesForRegion
Set<PhoneNumberUtil.PhoneNumberType> getSupportedTypesForRegion(String regionCode)
Returns the types for a given region which the library has metadata for. Will not includeFIXED_LINE_OR_MOBILE (if numbers in this region could be classified as FIXED_LINE_OR_MOBILE,both FIXED_LINE and MOBILE would be present) and UNKNOWN.No types will be returned for invalid or unknown region codes.
-
getSupportedTypesForNonGeoEntity
Set<PhoneNumberUtil.PhoneNumberType> getSupportedTypesForNonGeoEntity(int countryCallingCode)
Returns the types for a country-code belonging to a non-geographical entity which the libraryhas metadata for. Will not include FIXED_LINE_OR_MOBILE (if numbers for this non-geographicalentity could be classified as FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would bepresent) and UNKNOWN.No types will be returned for country calling codes that do not map to a known non-geographicalentity.
-
createInstance
static PhoneNumberUtil createInstance(MetadataLoader metadataLoader)
Create a new PhoneNumberUtil instance to carry out international phone numberformatting, parsing, or validation. The instance is loaded with all metadata byusing the metadataLoader specified.
This method should only be used in the rare case in which you want to manage your ownmetadata loading. Calling this method multiple times is very expensive, as each timea new instance is created from scratch.
- Parameters:
metadataLoader- customized metadata loader.
-
createInstance
static PhoneNumberUtil createInstance(Context context)
Create a new PhoneNumberUtil instance to carry out international phone numberformatting, parsing, or validation. The instance is loaded with all metadata byusing the context specified.
This method should only be used in the rare case in which you want to manage your ownmetadata loading. Calling this method multiple times is very expensive, as each timea new instance is created from scratch.
- Parameters:
context- Android Context used to load metadata.
-
isNumberGeographical
boolean isNumberGeographical(Phonenumber.PhoneNumber phoneNumber)
Tests whether a phone number has a geographical association. It checks if the number isassociated with a certain region in the country to which it belongs. Note that this doesn'tverify if the number is actually in use.
-
isNumberGeographical
boolean isNumberGeographical(PhoneNumberUtil.PhoneNumberType phoneNumberType, int countryCallingCode)
Overload of isNumberGeographical(PhoneNumber), since calculating the phone number type isexpensive; if we have already done this, we don't want to do it again.
-
format
String format(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat)
Formats a phone number in the specified format using default rules. Note that this does notpromise to produce a phone number that the user can dial from where they are - although we doformat in either 'national' or 'international' format depending on what the client asks for, wedo not currently support a more abbreviated format, such as for users in the same "area" whocould potentially dial the number without area code. Note that if the phone number has acountry calling code of 0 or an otherwise invalid country calling code, we cannot work outwhich formatting rules to apply so we return the national significant number with no formattingapplied.
- Parameters:
number- the phone number to be formattednumberFormat- the format the phone number should be formatted into
-
format
void format(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, StringBuilder formattedNumber)
Same as format, but accepts a mutable StringBuilder asa parameter to decrease object creation when invoked many times.
-
formatByPattern
String formatByPattern(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberFormat numberFormat, List<Phonemetadata.NumberFormat> userDefinedFormats)
Formats a phone number in the specified format using client-defined formatting rules. Note thatif the phone number has a country calling code of zero or an otherwise invalid country callingcode, we cannot work out things like whether there should be a national prefix applied, or howto format extensions, so we return the national significant number with no formatting applied.
- Parameters:
number- the phone number to be formattednumberFormat- the format the phone number should be formatted intouserDefinedFormats- formatting rules specified by clients
-
formatNationalNumberWithCarrierCode
String formatNationalNumberWithCarrierCode(Phonenumber.PhoneNumber number, CharSequence carrierCode)
Formats a phone number in national format for dialing using the carrier as specified in the
{@code carrierCode}. The{@code carrierCode}will always be used regardless of whether thephone number already has a preferred domestic carrier code stored. If{@code carrierCode}contains an empty string, returns the number in national format without any carrier code.- Parameters:
number- the phone number to be formattedcarrierCode- the carrier selection code to be used
-
formatNationalNumberWithPreferredCarrierCode
String formatNationalNumberWithPreferredCarrierCode(Phonenumber.PhoneNumber number, CharSequence fallbackCarrierCode)
Formats a phone number in national format for dialing using the carrier as specified in thepreferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,use the
{@code fallbackCarrierCode}passed in instead. If there is no{@code preferredDomesticCarrierCode}, and the{@code fallbackCarrierCode}contains an emptystring, return the number in national format without any carrier code.Use formatNationalNumberWithCarrierCode instead if the carrier code passed inshould take precedence over the number's
{@code preferredDomesticCarrierCode}when formatting.- Parameters:
number- the phone number to be formattedfallbackCarrierCode- the carrier selection code to be used, if none is found in thephone number itself
-
formatNumberForMobileDialing
String formatNumberForMobileDialing(Phonenumber.PhoneNumber number, String regionCallingFrom, boolean withFormatting)
Returns a number formatted in such a way that it can be dialed from a mobile phone in aspecific region. If the number cannot be reached from the region (e.g. some countries blocktoll-free numbers from being called outside of the country), the method returns an emptystring.
- Parameters:
number- the phone number to be formattedregionCallingFrom- the region where the call is being placedwithFormatting- whether the number should be returned with formatting symbols, such asspaces and dashes.
-
formatOutOfCountryCallingNumber
String formatOutOfCountryCallingNumber(Phonenumber.PhoneNumber number, String regionCallingFrom)
Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom issupplied, we format the number in its INTERNATIONAL format. If the country calling code is thesame as that of the region where the number is from, then NATIONAL formatting will be applied.
If the number itself has a country calling code of zero or an otherwise invalid countrycalling code, then we return the number with no formatting applied.
Note this function takes care of the case for calling inside of NANPA and between Russia andKazakhstan (who share the same country calling code). In those cases, no international prefixis used. For regions which have multiple international prefixes, the number in itsINTERNATIONAL format will be returned instead.
- Parameters:
number- the phone number to be formattedregionCallingFrom- the region where the call is being placed
-
formatInOriginalFormat
String formatInOriginalFormat(Phonenumber.PhoneNumber number, String regionCallingFrom)
Formats a phone number using the original phone number format (e.g. INTERNATIONAL or NATIONAL)that the number is parsed from, provided that the number has been parsed with . Otherwise the number will be formatted in NATIONAL format.
The original format is embedded in the country_code_source field of the PhoneNumber objectpassed in, which is only set when parsing keeps the raw input. When we don't have a formattingpattern for the number, the method falls back to returning the raw input.
Note this method guarantees no digit will be inserted, removed or modified as a result offormatting.
- Parameters:
number- the phone number that needs to be formatted in its original number formatregionCallingFrom- the region whose IDD needs to be prefixed if the original number hasone
-
formatOutOfCountryKeepingAlphaChars
String formatOutOfCountryKeepingAlphaChars(Phonenumber.PhoneNumber number, String regionCallingFrom)
Formats a phone number for out-of-country dialing purposes.Note that in this version, if the number was entered originally using alpha characters andthis version of the number is stored in raw_input, this representation of the number will beused rather than the digit representation. Grouping information, as specified by characterssuch as "-" and " ", will be retained.
Caveats:
- This will not produce good results if the country calling code is both present in the rawinput _and_ is the start of the national number. This is not a problem in the regionswhich typically use alpha numbers.
- This will also not produce good results if the raw input has any grouping informationwithin the first three digits of the national number, and if the function needs to strippreceding digits/words in the raw input before these digits. Normally people group thefirst three digits together so this is not a huge problem - and will be fixed if itproves to be so.
- Parameters:
number- the phone number that needs to be formattedregionCallingFrom- the region where the call is being placed
-
getNationalSignificantNumber
String getNationalSignificantNumber(Phonenumber.PhoneNumber number)
Gets the national significant number of a phone number. Note a national significant numberdoesn't contain a national prefix or any formatting.
- Parameters:
number- the phone number for which the national significant number is needed
-
getExampleNumber
Phonenumber.PhoneNumber getExampleNumber(String regionCode)
Gets a valid number for the specified region.
- Parameters:
regionCode- the region for which an example number is needed
-
getInvalidExampleNumber
Phonenumber.PhoneNumber getInvalidExampleNumber(String regionCode)
Gets an invalid number for the specified region. This is useful for unit-testing purposes,where you want to test what will happen with an invalid number. Note that the number that isreturned will always be able to be parsed and will have the correct country code. It may alsobe a valid *short* number/code for this region. Validity checking such numbers is handled with io.michaelrocks.libphonenumber.android.ShortNumberInfo.
- Parameters:
regionCode- the region for which an example number is needed
-
getExampleNumberForType
Phonenumber.PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberUtil.PhoneNumberType type)
Gets a valid number for the specified region and number type.
- Parameters:
regionCode- the region for which an example number is neededtype- the type of number that is needed
-
getExampleNumberForType
Phonenumber.PhoneNumber getExampleNumberForType(PhoneNumberUtil.PhoneNumberType type)
Gets a valid number for the specified number type (it may belong to any country).
- Parameters:
type- the type of number that is needed
-
getExampleNumberForNonGeoEntity
Phonenumber.PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode)
Gets a valid number for the specified country calling code for a non-geographical entity.
- Parameters:
countryCallingCode- the country calling code for a non-geographical entity
-
getNumberType
PhoneNumberUtil.PhoneNumberType getNumberType(Phonenumber.PhoneNumber number)
Gets the type of a valid phone number.
- Parameters:
number- the phone number that we want to know the type
-
isValidNumber
boolean isValidNumber(Phonenumber.PhoneNumber number)
Tests whether a phone number matches a valid pattern. Note this doesn't verify the numberis actually in use, which is impossible to tell by just looking at a number itself. It onlyverifies whether the parsed, canonicalised number is valid: not whether a particular series ofdigits entered by the user is diallable from the region provided when parsing. For example, thenumber +41 (0) 78 927 2696 can be parsed into a number with country code "41" and nationalsignificant number "789272696". This is valid, while the original string is not diallable.
- Parameters:
number- the phone number that we want to validate
-
isValidNumberForRegion
boolean isValidNumberForRegion(Phonenumber.PhoneNumber number, String regionCode)
Tests whether a phone number is valid for a certain region. Note this doesn't verify the numberis actually in use, which is impossible to tell by just looking at a number itself. If thecountry calling code is not the same as the country calling code for the region, thisimmediately exits with false. After this, the specific number pattern rules for the region areexamined. This is useful for determining for example whether a particular number is valid forCanada, rather than just a valid NANPA number.Warning: In most cases, you want to use isValidNumber instead. For example, thismethod will mark numbers from British Crown dependencies such as the Isle of Man as invalid forthe region "GB" (United Kingdom), since it has its own region code, "IM", which may beundesirable.
- Parameters:
number- the phone number that we want to validateregionCode- the region that we want to validate the phone number for
-
getRegionCodeForNumber
String getRegionCodeForNumber(Phonenumber.PhoneNumber number)
Returns the region where a phone number is from. This could be used for geocoding at the regionlevel. Only guarantees correct results for valid, full numbers (not short-codes, or invalidnumbers).
- Parameters:
number- the phone number whose origin we want to know
-
getRegionCodeForCountryCode
String getRegionCodeForCountryCode(int countryCallingCode)
Returns the region code that matches the specific country calling code. In the case of noregion code being found, ZZ will be returned. In the case of multiple regions, the onedesignated in the metadata as the "main" region for this calling code will be returned. If thecountryCallingCode entered is valid but doesn't match a specific region (such as in the case ofnon-geographical calling codes like 800) the value "001" will be returned (corresponding tothe value for World in the UN M.49 schema).
-
getRegionCodesForCountryCode
List<String> getRegionCodesForCountryCode(int countryCallingCode)
Returns a list with the region codes that match the specific country calling code. Fornon-geographical country calling codes, the region code 001 is returned. Also, in the caseof no region code being found, an empty list is returned.
-
getCountryCodeForRegion
int getCountryCodeForRegion(String regionCode)
Returns the country calling code for a specific region. For example, this would be 1 for theUnited States, and 64 for New Zealand.
- Parameters:
regionCode- the region that we want to get the country calling code for
-
getNddPrefixForRegion
String getNddPrefixForRegion(String regionCode, boolean stripNonDigits)
Returns the national dialling prefix for a specific region. For example, this would be 1 forthe United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"(which indicates a wait for a dialling tone) from the prefix returned. If no national prefix ispresent, we return null.
Warning: Do not use this method for do-your-own formatting - for some regions, thenational dialling prefix is used only for certain types of numbers. Use the library'sformatting functions to prefix the national prefix when required.
- Parameters:
regionCode- the region that we want to get the dialling prefix forstripNonDigits- true to strip non-digits from the national dialling prefix
-
isNANPACountry
boolean isNANPACountry(String regionCode)
Checks if this is a region under the North American Numbering Plan Administration (NANPA).
-
isAlphaNumber
boolean isAlphaNumber(CharSequence number)
Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanitynumber will start with at least 3 digits and will have three or more alpha characters. Thisdoes not do region-specific checks - to work out if this number is actually valid for a region,it should be parsed and methods such as isPossibleNumberWithReason and isValidNumber should be used.
- Parameters:
number- the number that needs to be checked
-
isPossibleNumber
boolean isPossibleNumber(Phonenumber.PhoneNumber number)
Convenience wrapper around isPossibleNumberWithReason. Instead of returning the reasonfor failure, this method returns true if the number is either a possible fully-qualified number(containing the area code and country code), or if the number could be a possible local number(with a country code, but missing an area code). Local numbers are considered possible if theycould be possibly dialled in this format: if the area code is needed for a call to connect, thenumber is not considered possible without it.
- Parameters:
number- the number that needs to be checked
-
isPossibleNumberForType
boolean isPossibleNumberForType(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberType type)
Convenience wrapper around isPossibleNumberForTypeWithReason. Instead of returning thereason for failure, this method returns true if the number is either a possible fully-qualifiednumber (containing the area code and country code), or if the number could be a possible localnumber (with a country code, but missing an area code). Local numbers are considered possibleif they could be possibly dialled in this format: if the area code is needed for a call toconnect, the number is not considered possible without it.
- Parameters:
number- the number that needs to be checkedtype- the type we are interested in
-
isPossibleNumberWithReason
PhoneNumberUtil.ValidationResult isPossibleNumberWithReason(Phonenumber.PhoneNumber number)
Check whether a phone number is a possible number. It provides a more lenient check than isValidNumber in the following sense:
- It only checks the length of phone numbers. In particular, it doesn't check startingdigits of the number.
- It doesn't attempt to figure out the type of the number, but uses general rules whichapplies to all types of phone numbers in a region. Therefore, it is much faster thanisValidNumber.
- For some numbers (particularly fixed-line), many regions have the concept of area code,which together with subscriber number constitute the national significant number. It issometimes okay to dial only the subscriber number when dialing in the same area. Thisfunction will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version ispassed in. On the other hand, because isValidNumber validates using information on bothstarting digits (for fixed line numbers, that would most likely be area codes) andlength (obviously includes the length of area codes for fixed line numbers), it willreturn false for the subscriber-number-only version.
There is a known issue with thismethod: if a number is possible only in a certain region among several regions that share thesame country calling code, this method will consider only the "main" region. For example,+1310xxxx are valid numbers in Canada. However, they are not possible in the US. As a result,this method will return IS_POSSIBLE_LOCAL_ONLY for +1310xxxx.
- Parameters:
number- the number that needs to be checked
-
isPossibleNumberForTypeWithReason
PhoneNumberUtil.ValidationResult isPossibleNumberForTypeWithReason(Phonenumber.PhoneNumber number, PhoneNumberUtil.PhoneNumberType type)
Check whether a phone number is a possible number of a particular type. For types that don'texist in a particular region, this will return a result that isn't so useful; it is recommendedthat you use getSupportedTypesForRegion or getSupportedTypesForNonGeoEntity respectively before calling this method to determine whether you should call it for this numberat all.This provides a more lenient check than isValidNumber in the following sense:
- It only checks the length of phone numbers. In particular, it doesn't check startingdigits of the number.
- For some numbers (particularly fixed-line), many regions have the concept of area code,which together with subscriber number constitute the national significant number. It issometimes okay to dial only the subscriber number when dialing in the same area. Thisfunction will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version ispassed in. On the other hand, because isValidNumber validates using information on bothstarting digits (for fixed line numbers, that would most likely be area codes) andlength (obviously includes the length of area codes for fixed line numbers), it willreturn false for the subscriber-number-only version.
There is a known issue with thismethod: if a number is possible only in a certain region among several regions that share thesame country calling code, this method will consider only the "main" region. For example,+1310xxxx are valid numbers in Canada. However, they are not possible in the US. As a result,this method will return IS_POSSIBLE_LOCAL_ONLY for +1310xxxx.
- Parameters:
number- the number that needs to be checkedtype- the type we are interested in
-
isPossibleNumber
boolean isPossibleNumber(CharSequence number, String regionDialingFrom)
Check whether a phone number is a possible number given a number in the form of a string, andthe region where the number could be dialed from. It provides a more lenient check than isValidNumber. See isPossibleNumber for details.
This method first parses the number, then invokes isPossibleNumber with the resultant PhoneNumber object.
- Parameters:
number- the number that needs to be checkedregionDialingFrom- the region that we are expecting the number to be dialed from.Note this is different from the region where the number belongs.
-
truncateTooLongNumber
boolean truncateTooLongNumber(Phonenumber.PhoneNumber number)
Attempts to extract a valid number from a phone number that is too long to be valid, and resetsthe PhoneNumber object passed in to that valid version. If no valid number could be extracted,the PhoneNumber object passed in will not be modified.
- Parameters:
number- a PhoneNumber object which contains a number that is too long to be valid
-
getAsYouTypeFormatter
AsYouTypeFormatter getAsYouTypeFormatter(String regionCode)
Gets an io.michaelrocks.libphonenumber.android.AsYouTypeFormatter for the specific region.
- Parameters:
regionCode- the region where the phone number is being entered
-
parse
Phonenumber.PhoneNumber parse(CharSequence numberToParse, String defaultRegion)
Parses a string and returns it as a phone number in proto buffer format. The method is quitelenient and looks for a number in the input text (raw input) and does not check whether thestring is definitely only a phone number. To do this, it ignores punctuation and white-space,as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits.It will accept a number in any format (E164, national, international etc), assuming it can beinterpreted with the defaultRegion supplied. It also attempts to convert any alpha charactersinto digits if it thinks this is a vanity number of the type "1800 MICROSOFT".
This method will throw a io.michaelrocks.libphonenumber.android.NumberParseException if thenumber is not considered to be a possible number. Note that validation of whether the numberis actually a valid number for a particular region is not performed. This can be doneseparately with isValidNumber.
Note this method canonicalizes the phone number such that different representations can beeasily compared, no matter what form it was originally entered in (e.g. national,international). If you want to record context about the number being parsed, such as the rawinput that was entered, how the country code was derived etc. then call instead.
- Parameters:
numberToParse- number that we are attempting to parse.defaultRegion- region that we are expecting the number to be from.
-
parse
void parse(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber)
Same as parse, but accepts mutable PhoneNumber as aparameter to decrease object creation when invoked many times.
-
parseAndKeepRawInput
Phonenumber.PhoneNumber parseAndKeepRawInput(CharSequence numberToParse, String defaultRegion)
Parses a string and returns it in proto buffer format. This method differs from parse in that it always populates the raw_input field of the protocol buffer with numberToParse aswell as the country_code_source field.
- Parameters:
numberToParse- number that we are attempting to parse.defaultRegion- region that we are expecting the number to be from.
-
parseAndKeepRawInput
void parseAndKeepRawInput(CharSequence numberToParse, String defaultRegion, Phonenumber.PhoneNumber phoneNumber)
Same asparseAndKeepRawInput, but accepts a mutablePhoneNumber as a parameter to decrease object creation when invoked many times.
-
findNumbers
Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion)
Returns an iterable over all PhoneNumberMatches in
{@code text}. Thisis a shortcut for getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE).- Parameters:
text- the text to search for phone numbers, null for no textdefaultRegion- region that we are expecting the number to be from.
-
findNumbers
Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion, PhoneNumberUtil.Leniency leniency, long maxTries)
Returns an iterable over all PhoneNumberMatches in
{@code text}.- Parameters:
text- the text to search for phone numbers, null for no textdefaultRegion- region that we are expecting the number to be from.leniency- the leniency to use when evaluating candidate phone numbersmaxTries- the maximum number of invalid numbers to try before giving up on the text.This is to cover degenerate cases where the text has a lot of false positives in it.
-
isNumberMatch
PhoneNumberUtil.MatchType isNumberMatch(Phonenumber.PhoneNumber firstNumberIn, Phonenumber.PhoneNumber secondNumberIn)
Takes two phone numbers and compares them for equality.
Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbersand any extension present are the same.Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions arethe same.Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified isthe same, and one NSN could be a shorter version of the other number. This includes the casewhere one has an extension specified, and the other does not.Returns NO_MATCH otherwise.For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
- Parameters:
firstNumberIn- first number to comparesecondNumberIn- second number to compare
-
isNumberMatch
PhoneNumberUtil.MatchType isNumberMatch(CharSequence firstNumber, CharSequence secondNumber)
Takes two phone numbers as strings and compares them for equality. This is a conveniencewrapper for isNumberMatch. No default region is known.
- Parameters:
firstNumber- first number to compare.secondNumber- second number to compare.
-
isNumberMatch
PhoneNumberUtil.MatchType isNumberMatch(Phonenumber.PhoneNumber firstNumber, CharSequence secondNumber)
Takes two phone numbers and compares them for equality. This is a convenience wrapper for isNumberMatch. No default region is known.
- Parameters:
firstNumber- first number to compare in proto buffer formatsecondNumber- second number to compare.
-
canBeInternationallyDialled
boolean canBeInternationallyDialled(Phonenumber.PhoneNumber number)
Returns true if the number can be dialled from outside the region, or unknown. If the numbercan only be dialled from within the region, returns false. Does not check the number is a validnumber. Note that, at the moment, this method does not handle short numbers (which arecurrently all presumed to not be diallable from outside their country).
- Parameters:
number- the phone-number for which we want to know whether it is diallable fromoutside the region
-
isMobileNumberPortableRegion
boolean isMobileNumberPortableRegion(String regionCode)
Returns true if the supplied region supports mobile number portability. Returns false forinvalid, unknown or regions that don't support mobile number portability.
- Parameters:
regionCode- the region for which we want to know whether it supports mobile numberportability or not
-
-
-
-