Java Code Examples for com.google.i18n.phonenumbers.PhoneNumberUtil
The following examples show how to use
com.google.i18n.phonenumbers.PhoneNumberUtil.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: mollyim-android Author: mollyim File: PhoneNumberFormatter.java License: GNU General Public License v3.0 | 6 votes |
public static boolean isValidNumber(String e164Number, String countryCode) { if (!PhoneNumberUtil.getInstance().isPossibleNumber(e164Number, countryCode)) { Log.w(TAG, "Failed isPossibleNumber()"); return false; } if (COUNTRY_CODE_US.equals(countryCode) && !Pattern.matches("^\\+1[0-9]{10}$", e164Number)) { Log.w(TAG, "Failed US number format check"); return false; } if (COUNTRY_CODE_BR.equals(countryCode) && !Pattern.matches("^\\+55[0-9]{2}9?[0-9]{8}$", e164Number)) { Log.w(TAG, "Failed Brazil number format check"); return false; } return e164Number.matches("^\\+[1-9][0-9]{6,14}$"); }
Example #2
Source Project: mollyim-android Author: mollyim File: PhoneNumberFormatter.java License: GNU General Public License v3.0 | 6 votes |
public static String formatE164(String countryCode, String number) { try { PhoneNumberUtil util = PhoneNumberUtil.getInstance(); int parsedCountryCode = Integer.parseInt(countryCode); PhoneNumber parsedNumber = util.parse(number, util.getRegionCodeForCountryCode(parsedCountryCode)); return util.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164); } catch (NumberParseException | NumberFormatException npe) { Log.w(TAG, npe); } return "+" + countryCode.replaceAll("[^0-9]", "").replaceAll("^0*", "") + number.replaceAll("[^0-9]", ""); }
Example #3
Source Project: mollyim-android Author: mollyim File: EnterPhoneNumberFragment.java License: GNU General Public License v3.0 | 6 votes |
private void initNumber(@NonNull NumberViewState numberViewState) { int countryCode = numberViewState.getCountryCode(); long number = numberViewState.getNationalNumber(); String regionDisplayName = numberViewState.getCountryDisplayName(); this.countryCode.setText(String.valueOf(countryCode)); setCountryDisplay(regionDisplayName); String regionCode = PhoneNumberUtil.getInstance().getRegionCodeForCountryCode(countryCode); setCountryFormatter(regionCode); if (number != 0) { this.number.setText(String.valueOf(number)); } }
Example #4
Source Project: mollyim-android Author: mollyim File: EnterPhoneNumberFragment.java License: GNU General Public License v3.0 | 6 votes |
@Override public void afterTextChanged(Editable s) { if (TextUtils.isEmpty(s) || !TextUtils.isDigitsOnly(s)) { setCountryDisplay(null); countryFormatter = null; return; } int countryCode = Integer.parseInt(s.toString()); String regionCode = PhoneNumberUtil.getInstance().getRegionCodeForCountryCode(countryCode); setCountryFormatter(regionCode); if (!TextUtils.isEmpty(regionCode) && !regionCode.equals("ZZ")) { number.requestFocus(); int numberLength = number.getText().length(); number.getInput().setSelection(numberLength, numberLength); } RegistrationViewModel model = getModel(); model.onCountrySelected(null, countryCode); setCountryDisplay(model.getNumber().getCountryDisplayName()); }
Example #5
Source Project: mollyim-android Author: mollyim File: WelcomeFragment.java License: GNU General Public License v3.0 | 6 votes |
@SuppressLint("MissingPermission") private void initializeNumber() { Optional<Phonenumber.PhoneNumber> localNumber = Optional.absent(); if (Permissions.hasAll(requireContext(), Manifest.permission.READ_PHONE_STATE)) { localNumber = Util.getDeviceNumber(requireContext()); } if (localNumber.isPresent()) { getModel().onNumberDetected(localNumber.get().getCountryCode(), localNumber.get().getNationalNumber()); } else { Optional<String> simCountryIso = Util.getSimCountryIso(requireContext()); if (simCountryIso.isPresent() && !TextUtils.isEmpty(simCountryIso.get())) { getModel().onNumberDetected(PhoneNumberUtil.getInstance().getCountryCodeForRegion(simCountryIso.get()), 0); } } }
Example #6
Source Project: mollyim-android Author: mollyim File: NumberViewState.java License: GNU General Public License v3.0 | 6 votes |
public String getCountryDisplayName() { if (selectedCountryName != null) { return selectedCountryName; } PhoneNumberUtil util = PhoneNumberUtil.getInstance(); if (isValid()) { String actualCountry = getActualCountry(util, getE164Number()); if (actualCountry != null) { return actualCountry; } } String regionCode = util.getRegionCodeForCountryCode(countryCode); return PhoneNumberFormatter.getRegionDisplayName(regionCode); }
Example #7
Source Project: mollyim-android Author: mollyim File: ShortCodeUtil.java License: GNU General Public License v3.0 | 6 votes |
public static boolean isShortCode(@NonNull String localNumber, @NonNull String number) { try { PhoneNumberUtil util = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber localNumberObject = util.parse(localNumber, null); String localCountryCode = util.getRegionCodeForNumber(localNumberObject); String bareNumber = number.replaceAll("[^0-9+]", ""); // libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes. if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) { return true; } Phonenumber.PhoneNumber shortCode = util.parse(number, localCountryCode); return ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(shortCode, localCountryCode); } catch (NumberParseException e) { Log.w(TAG, e); return false; } }
Example #8
Source Project: mollyim-android Author: mollyim File: Util.java License: GNU General Public License v3.0 | 6 votes |
@RequiresPermission(anyOf = { android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.READ_SMS, android.Manifest.permission.READ_PHONE_NUMBERS }) @SuppressLint("MissingPermission") public static Optional<Phonenumber.PhoneNumber> getDeviceNumber(Context context) { try { final String localNumber = ((TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number(); final Optional<String> countryIso = getSimCountryIso(context); if (TextUtils.isEmpty(localNumber)) return Optional.absent(); if (!countryIso.isPresent()) return Optional.absent(); return Optional.fromNullable(PhoneNumberUtil.getInstance().parse(localNumber, countryIso.get())); } catch (NumberParseException e) { Log.w(TAG, e); return Optional.absent(); } }
Example #9
Source Project: keycloak-extension-playground Author: thomasdarimont File: MobileValidation.java License: Apache License 2.0 | 6 votes |
static boolean isPhoneNumberValid(String phoneNumber) { String formattedPhoneNumber = convertInternationalPrefix(phoneNumber); String region; if (isPossibleNationalNumber(formattedPhoneNumber)) { region = "DE"; } else if (isInternationalNumber(formattedPhoneNumber)) { region = null; } else { return true; // If the number cannot be interpreted as an international or possible DE phone number, do not attempt to validate it. } try { Phonenumber.PhoneNumber parsedPhoneNumber = PhoneNumberUtil.getInstance().parse(formattedPhoneNumber, region); return PhoneNumberUtil.getInstance().isValidNumber(parsedPhoneNumber); } catch (NumberParseException e) { return false; } }
Example #10
Source Project: Android Author: bhavyakaria File: MainActivity.java License: MIT License | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber indianPhoneNumber = null; try { indianPhoneNumber = phoneNumberUtil.parse(phoneNumber, "IN"); boolean val = phoneNumberUtil.isValidNumber(indianPhoneNumber); Log.d("Parzival", "Data: "+indianPhoneNumber.getCountryCode()+" >> "+indianPhoneNumber.getNationalNumber()); Log.d("Parzival", "Val: "+val); } catch (NumberParseException e) { e.printStackTrace(); } }
Example #11
Source Project: call_manage Author: Chooloo File: Utilities.java License: MIT License | 6 votes |
/** * Format a given phone number to a readable string for the user * * @param phoneNumber the number to format * @return the formatted number */ public static String formatPhoneNumber(String phoneNumber) { if (phoneNumber == null) return null; phoneNumber = normalizePhoneNumber(phoneNumber); Phonenumber.PhoneNumber formattedNumber = null; PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); try { formattedNumber = phoneUtil.parse(phoneNumber, sLocale.getCountry()); } catch (NumberParseException e) { Timber.w(e); return phoneNumber; } PhoneNumberUtil.PhoneNumberFormat format; if (phoneUtil.getRegionCodeForCountryCode(formattedNumber.getCountryCode()).equals(sLocale.getCountry())) format = PhoneNumberUtil.PhoneNumberFormat.NATIONAL; else format = PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL; return phoneUtil.format(formattedNumber, format); }
Example #12
Source Project: weMessage Author: RomanScott File: MessagesDatabase.java License: GNU Affero General Public License v3.0 | 6 votes |
public Handle getHandleByAccount(String account) throws SQLException { try { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber numberOne = phoneNumberUtil.parse(account, Locale.getDefault().getCountry()); String numberStringOne = phoneNumberUtil.format(numberOne, PhoneNumberUtil.PhoneNumberFormat.E164); Handle handle = getHandleById(numberStringOne); if (handle == null){ Phonenumber.PhoneNumber numberTwo = numberOne.clearCountryCode(); String numberStringTwo = phoneNumberUtil.format(numberTwo, PhoneNumberUtil.PhoneNumberFormat.E164).substring(2); return getHandleById(numberStringTwo); }else { return handle; } }catch(Exception ex){ return getHandleById(account); } }
Example #13
Source Project: weMessage Author: RomanScott File: Handle.java License: GNU Affero General Public License v3.0 | 6 votes |
public static String parseHandleId(String handleID){ PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String locale = Resources.getSystem().getConfiguration().locale.getCountry(); String returnHandle; if (phoneNumberUtil.isPossibleNumber(handleID, locale)){ try { Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(handleID, locale); returnHandle = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164); }catch (Exception ex){ returnHandle = handleID; } } else { returnHandle = handleID.trim().toLowerCase(); } return returnHandle; }
Example #14
Source Project: customview-samples Author: hyhdy File: ContactFragment.java License: Apache License 2.0 | 6 votes |
private void displayContactData(){ List<PhoneInfo> phoneInfoList = MobileContactSingleton.getInstance().getMobileContact(); PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); for(PhoneInfo phoneInfo: phoneInfoList) { try { String phoneNum = phoneInfo.getPhoneNum(); Phonenumber.PhoneNumber phoneNumProto = phoneUtil.parse(phoneNum, "CN"); boolean isValid = phoneUtil.isValidNumber(phoneNumProto); Log.d("hyh", "ContactFragment: displayContactData: isValid="+isValid+" ,phoneNum="+phoneNum); if (isValid) { String formatPhoneNum = phoneUtil.format(phoneNumProto, PhoneNumberUtil.PhoneNumberFormat.E164); Log.d("hyh", "ContactMgr: run: formatPhoneNum=" + formatPhoneNum); } } catch (NumberParseException e) { Log.d("hyh", "ContactFragment: displayContactData: phone="+phoneInfo.getPhoneNum()); e.printStackTrace(); } } ContactListAdapter contactListAdapter = new ContactListAdapter(getContext(),phoneInfoList); mRvContactList.setLayoutManager(new LinearLayoutManager(getContext())); mRvContactList.setAdapter(contactListAdapter); }
Example #15
Source Project: XERUNG Author: mityung File: SignIn.java License: Apache License 2.0 | 6 votes |
private void sendOTPNumber(){ if(checkNull()){ PhoneNumberUtil util = PhoneNumberUtil.getInstance(); // assuming you only a button in your layout... boolean isAuthentic = false; try { PhoneNumber number = util.parse(countryPrefix + edtMobile.getText().toString().trim(), countryIso); isAuthentic = true; } catch (NumberParseException e) { e.printStackTrace(); } if (isAuthentic) { comman.hideSoftKeyBoard(context, edtMobile); createJson(edtMobile.getText().toString().trim(), countryPrefix, countryName); } } }
Example #16
Source Project: XERUNG Author: mityung File: SignIn.java License: Apache License 2.0 | 6 votes |
private void sendOTPNumber(){ if(checkNull()){ PhoneNumberUtil util = PhoneNumberUtil.getInstance(); // assuming you only a button in your layout... boolean isAuthentic = false; try { PhoneNumber number = util.parse(countryPrefix + edtMobile.getText().toString().trim(), countryIso); isAuthentic = true; } catch (NumberParseException e) { e.printStackTrace(); } if (isAuthentic) { comman.hideSoftKeyBoard(context, edtMobile); createJson(edtMobile.getText().toString().trim(), countryPrefix, countryName); } } }
Example #17
Source Project: sunbird-lms-service Author: project-sunbird File: PhoneValidator.java License: MIT License | 6 votes |
public static boolean validatePhone(String phone, String countryCode) { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String code = countryCode; if (StringUtils.isNotBlank(countryCode) && (countryCode.charAt(0) != '+')) { code = "+" + countryCode; } Phonenumber.PhoneNumber phoneNumber = null; try { if (StringUtils.isBlank(countryCode)) { code = PropertiesCache.getInstance().getProperty("sunbird_default_country_code"); } String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(code)); phoneNumber = phoneNumberUtil.parse(phone, isoCode); return phoneNumberUtil.isValidNumber(phoneNumber); } catch (NumberParseException e) { ProjectLogger.log( "PhoneValidator:validatePhone: Exception occurred while validating phone number = ", e); } return false; }
Example #18
Source Project: sunbird-lms-service Author: project-sunbird File: ProjectUtil.java License: MIT License | 6 votes |
public static boolean validatePhone(String phNumber, String countryCode) { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String contryCode = countryCode; if (!StringUtils.isBlank(countryCode) && (countryCode.charAt(0) != '+')) { contryCode = "+" + countryCode; } Phonenumber.PhoneNumber phoneNumber = null; try { if (StringUtils.isBlank(countryCode)) { contryCode = PropertiesCache.getInstance().getProperty("sunbird_default_country_code"); } String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(contryCode)); phoneNumber = phoneNumberUtil.parse(phNumber, isoCode); return phoneNumberUtil.isValidNumber(phoneNumber); } catch (NumberParseException e) { ProjectLogger.log("Exception occurred while validating phone number : ", e); ProjectLogger.log(phNumber + "this phone no. is not a valid one."); } return false; }
Example #19
Source Project: mxisd Author: kamax-matrix File: GoogleFirebaseAuthenticator.java License: GNU Affero General Public License v3.0 | 6 votes |
private void toMsisdn(BackendAuthResult result, String phoneNumber) { if (StringUtils.isBlank(phoneNumber)) { return; } try { String number = phoneUtil.format( phoneUtil.parse( phoneNumber, null // No default region ), PhoneNumberUtil.PhoneNumberFormat.E164 ).substring(1); // We want without the leading + result.withThreePid(new ThreePid(ThreePidMedium.PhoneNumber.getId(), number)); } catch (NumberParseException e) { log.warn("Invalid phone number: {}", phoneNumber); } }
Example #20
Source Project: scipio-erp Author: ilscipio File: AddressUtil.java License: Apache License 2.0 | 6 votes |
/** * Validates phone numbers (using external library). * <p> * SCIPIO: 2018-08-30: Stock method moved here from {@link org.ofbiz.base.util.UtilValidate} * due to dependency issues. */ public static boolean isValidPhoneNumber(String phoneNumber, String geoId, Delegator delegator) { boolean isValid = false; try { GenericValue geo = EntityQuery.use(delegator).from("Geo").where("geoId", geoId).cache().queryOne(); PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); String geoCode = geo != null ? geo.getString("geoCode") : "US"; PhoneNumber phNumber = phoneUtil.parse(phoneNumber, geoCode); if (phoneUtil.isValidNumber(phNumber) || phoneUtil.isPossibleNumber(phNumber)) { isValid = true; } } catch (GenericEntityException | NumberParseException ex) { Debug.logError(ex, module); } return isValid; }
Example #21
Source Project: AirMapSDK-Android Author: airmap File: ExpandableAdvisoriesAdapter.java License: Apache License 2.0 | 6 votes |
private String formatPhoneNumber(Context context, String number) { if (TextUtils.isEmpty(number)) { return context.getString(R.string.no_known_number); } PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); Locale locale = Locale.getDefault(); String country = locale != null && locale.getCountry() != null && !TextUtils.isEmpty(locale.getCountry()) ? locale.getCountry() : "US"; try { Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(number, country); return phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL); } catch (NumberParseException e) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return PhoneNumberUtils.formatNumber(number, country); } return PhoneNumberUtils.formatNumber(number); } }
Example #22
Source Project: tindroid Author: tinode File: UiUtils.java License: Apache License 2.0 | 6 votes |
static Credential parseCredential(String cred) { final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); final String country = Locale.getDefault().getCountry(); if (Patterns.PHONE.matcher(cred).matches()) { // Looks like a phone number. try { // Normalize phone number format cred = phoneUtil.format(phoneUtil.parse(cred, country), PhoneNumberUtil.PhoneNumberFormat.E164); // Exception not thrown, we have a phone number. return new Credential(Credential.METH_PHONE, cred); } catch (NumberParseException ignored) { return null; } } // Not a phone number. Try parsing as email. if (Patterns.EMAIL_ADDRESS.matcher(cred).matches()) { return new Credential(Credential.METH_EMAIL, cred); } return null; }
Example #23
Source Project: YaMvp Author: Piasy File: MainPresenter.java License: MIT License | 6 votes |
private String validateThenFormatMobileNumber(String phone) { try { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(phone, "+86"); if (phoneNumberUtil.isValidNumber(phoneNumber) && ( phoneNumberUtil.getNumberType(phoneNumber) == PhoneNumberUtil.PhoneNumberType.MOBILE || phoneNumberUtil.getNumberType(phoneNumber) == PhoneNumberUtil.PhoneNumberType.FIXED_LINE_OR_MOBILE)) { return phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164); } else { return ""; } } catch (NumberParseException e) { return ""; } }
Example #24
Source Project: libsignal-service-java Author: signalapp File: PhoneNumberFormatter.java License: GNU General Public License v3.0 | 6 votes |
public static boolean isValidNumber(String e164Number, String countryCode) { if (!PhoneNumberUtil.getInstance().isPossibleNumber(e164Number, countryCode)) { Log.w(TAG, "Failed isPossibleNumber()"); return false; } if (COUNTRY_CODE_US.equals(countryCode) && !Pattern.matches("^\\+1[0-9]{10}$", e164Number)) { Log.w(TAG, "Failed US number format check"); return false; } if (COUNTRY_CODE_BR.equals(countryCode) && !Pattern.matches("^\\+55[0-9]{2}9?[0-9]{8}$", e164Number)) { Log.w(TAG, "Failed Brazil number format check"); return false; } return e164Number.matches("^\\+[1-9][0-9]{6,14}$"); }
Example #25
Source Project: libsignal-service-java Author: signalapp File: PhoneNumberFormatter.java License: GNU General Public License v3.0 | 6 votes |
public static String formatE164(String countryCode, String number) { try { PhoneNumberUtil util = PhoneNumberUtil.getInstance(); int parsedCountryCode = Integer.parseInt(countryCode); PhoneNumber parsedNumber = util.parse(number, util.getRegionCodeForCountryCode(parsedCountryCode)); return util.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164); } catch (NumberParseException | NumberFormatException npe) { Log.w(TAG, npe); } return "+" + countryCode.replaceAll("[^0-9]", "").replaceAll("^0*", "") + number.replaceAll("[^0-9]", ""); }
Example #26
Source Project: Silence Author: SilenceIM File: AutoInitiate.java License: GNU General Public License v3.0 | 6 votes |
public static boolean isTaggableDestination(Recipients recipients){ // Be safe - err on the side of not tagging if (recipients.isGroupRecipient()) return false; PhoneNumberUtil util = PhoneNumberUtil.getInstance(); try { PhoneNumber num = util.parse(recipients.getPrimaryRecipient().getNumber(), Locale.getDefault().getCountry()); PhoneNumberType type = util.getNumberType(num); Log.d(TAG, "Number type: " + type.toString()); return type == PhoneNumberType.FIXED_LINE || type == PhoneNumberType.MOBILE || type == PhoneNumberType.FIXED_LINE_OR_MOBILE; } catch (NumberParseException e){ Log.w(TAG, "Couldn't get number type (country: " + Locale.getDefault().getCountry() + ")"); return false; } }
Example #27
Source Project: Silence Author: SilenceIM File: CountryListLoader.java License: GNU General Public License v3.0 | 6 votes |
@Override public ArrayList<Map<String, String>> loadInBackground() { Set<String> regions = PhoneNumberUtil.getInstance().getSupportedRegions(); ArrayList<Map<String, String>> results = new ArrayList<Map<String, String>>(regions.size()); for (String region : regions) { Map<String, String> data = new HashMap<String, String>(2); data.put("country_name", PhoneNumberFormatter.getRegionDisplayName(region)); data.put("country_code", "+" +PhoneNumberUtil.getInstance().getCountryCodeForRegion(region)); results.add(data); } Collections.sort(results, new RegionComparator()); return results; }
Example #28
Source Project: Silence Author: SilenceIM File: ShortCodeUtil.java License: GNU General Public License v3.0 | 6 votes |
public static boolean isShortCode(@NonNull String localNumber, @NonNull String number) { try { PhoneNumberUtil util = PhoneNumberUtil.getInstance(); Phonenumber.PhoneNumber localNumberObject = util.parse(localNumber, null); String localCountryCode = util.getRegionCodeForNumber(localNumberObject); String bareNumber = number.replaceAll("[^0-9+]", ""); // libphonenumber doesn't seem to be correct for Germany and Finland if (bareNumber.length() <= 6 && ("DE".equals(localCountryCode) || "FI".equals(localCountryCode) || "SK".equals(localCountryCode))) { return true; } // libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes. if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) { return true; } Phonenumber.PhoneNumber shortCode = util.parse(number, localCountryCode); return ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(shortCode, localCountryCode); } catch (NumberParseException e) { Log.w(TAG, e); return false; } }
Example #29
Source Project: Silence Author: SilenceIM File: PhoneNumberFormatter.java License: GNU General Public License v3.0 | 6 votes |
public static String formatE164(String countryCode, String number) { try { PhoneNumberUtil util = PhoneNumberUtil.getInstance(); int parsedCountryCode = Integer.parseInt(countryCode); PhoneNumber parsedNumber = util.parse(number, util.getRegionCodeForCountryCode(parsedCountryCode)); return util.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164); } catch (NumberParseException | NumberFormatException npe) { Log.w(TAG, npe); } return "+" + countryCode.replaceAll("[^0-9]", "").replaceAll("^0*", "") + number.replaceAll("[^0-9]", ""); }
Example #30
Source Project: endpoints-codelab-android Author: GoogleCloudPlatform File: PhoneNumberParser.java License: GNU General Public License v3.0 | 6 votes |
public List<String> parse(String inputText) { if (inputText == null) { return Collections.emptyList(); } // Only run the phone number parser if Android version is not Honeycomb // API level 11 - 13 int sdk = Build.VERSION.SDK_INT; if (sdk >= 11 && sdk <= 13) { return Collections.emptyList(); } PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); Iterable<PhoneNumberMatch> numbersMatch = phoneUtil.findNumbers( inputText, Locale.getDefault().getCountry()); ArrayList<String> numbers = new ArrayList<String>(); for (PhoneNumberMatch number : numbersMatch) { numbers.add(phoneUtil.format(number.number(), PhoneNumberFormat.NATIONAL)); } return numbers; }