com.google.i18n.phonenumbers.PhoneNumberUtil Java Examples

The following examples show how to use com.google.i18n.phonenumbers.PhoneNumberUtil. 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 File: Handle.java    From weMessage with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #2
Source File: WelcomeFragment.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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 #3
Source File: PhoneNumberParser.java    From endpoints-codelab-android with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: EnterPhoneNumberFragment.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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 File: EnterPhoneNumberFragment.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #6
Source File: Global.java    From Faceless with GNU General Public License v3.0 6 votes vote down vote up
public static String[] normalizeNumber(String phoneNumber, String defaultRegion) {
	PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
	PhoneNumber input;
	try {
		input = phoneUtil.parse(phoneNumber, defaultRegion.trim().toUpperCase(Locale.US));
		if (phoneUtil.isValidNumber(input)) {
			String parsedRegionCode = phoneUtil.getRegionCodeForNumber(input);
			if (parsedRegionCode != null) {
				return new String[] { phoneUtil.format(input, PhoneNumberUtil.PhoneNumberFormat.E164), parsedRegionCode };
			}
			else {
				return null;
			}
		}
		else {
			return null;
		}
	}
	catch (Exception e) {
		return null;
	}
}
 
Example #7
Source File: PhoneUtils.java    From android-phone-number-with-flags with Apache License 2.0 6 votes vote down vote up
private static String parseNumber(String paramString) {
    if (paramString == null) {
        return null;
    }
    PhoneNumberUtil numberUtil = PhoneNumberUtil.getInstance();
    String result;
    try {
        Phonenumber.PhoneNumber localPhoneNumber = numberUtil.parse(paramString, null);
        result = numberUtil.getRegionCodeForNumber(localPhoneNumber);
        if (result == null) {
            return null;
        }
    } catch (NumberParseException localNumberParseException) {
        return null;
    }
    return result;
}
 
Example #8
Source File: XMPPUtils.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
public static String phoneNumberToKontalkLocal(String number) {
    PhoneNumberUtil pnUtil = PhoneNumberUtil.getInstance();
    PhoneNumber n;
    try {
        n = pnUtil.parse(number, null);
    } catch (NumberParseException ex) {
        return "";
    }

    if (!pnUtil.isValidNumber(n))
        return "";

    return DigestUtils.sha1Hex(
            PhoneNumberUtil.getInstance().format(n,
            PhoneNumberUtil.PhoneNumberFormat.E164));
}
 
Example #9
Source File: PhoneNumberFormatter.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #10
Source File: LookupAsyncTask.java    From callerid-for-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onPreExecute() throws Exception {
	super.onPreExecute();
	address.setVisibility(View.GONE);
	if(layout.findViewById(R.id.map_view)!=null) layout.findViewById(R.id.map_view).setVisibility(View.GONE);
	image.setVisibility(View.VISIBLE);
	text.setVisibility(View.VISIBLE);
	
	final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
	try{
		final PhoneNumber phoneNumberPhoneNumber = phoneNumberUtil.parse(phoneNumber.toString(), countryDetector.getCountry());
		final PhoneNumberOfflineGeocoder phoneNumberOfflineGeocoder = PhoneNumberOfflineGeocoder.getInstance();
		offlineGeocoderResult = phoneNumberOfflineGeocoder.getDescriptionForNumber(phoneNumberPhoneNumber, Locale.getDefault());
	}catch(NumberParseException e){
		//ignore this exception
	}
	if("".equals(offlineGeocoderResult)) offlineGeocoderResult = null;
	if(offlineGeocoderResult == null)
		text.setText(lookupInProgress);
	else
		text.setText(offlineGeocoderResult);
	image.spin();
}
 
Example #11
Source File: Util.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@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 #12
Source File: MainActivity.java    From Android with MIT License 6 votes vote down vote up
@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 #13
Source File: Utilities.java    From call_manage with MIT License 6 votes vote down vote up
/**
 * 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 #14
Source File: MessagesDatabase.java    From weMessage with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #15
Source File: ShortCodeUtil.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
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 #16
Source File: PhoneNumberFormatter.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
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 #17
Source File: CountryListLoader.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
@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 #18
Source File: AutoInitiate.java    From Silence with GNU General Public License v3.0 6 votes vote down vote up
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 #19
Source File: ContactFragment.java    From customview-samples with Apache License 2.0 6 votes vote down vote up
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 #20
Source File: SignIn.java    From XERUNG with Apache License 2.0 6 votes vote down vote up
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 #21
Source File: PhoneNumberFormatter.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #22
Source File: SignIn.java    From XERUNG with Apache License 2.0 6 votes vote down vote up
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 #23
Source File: PhoneNumberFormatter.java    From libsignal-service-java with GNU General Public License v3.0 6 votes vote down vote up
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 #24
Source File: PhoneValidator.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
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 #25
Source File: ProjectUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
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 #26
Source File: MainPresenter.java    From YaMvp with MIT License 6 votes vote down vote up
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 #27
Source File: GoogleFirebaseAuthenticator.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #28
Source File: UiUtils.java    From tindroid with Apache License 2.0 6 votes vote down vote up
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 #29
Source File: AddressUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #30
Source File: ExpandableAdvisoriesAdapter.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
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);
    }
}