Java Code Examples for android.telephony.PhoneNumberUtils

The following examples show how to use android.telephony.PhoneNumberUtils. 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: AndroidWebServ   Source File: VCardContactEncoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String[] encode(Iterable<String> names, String organization, Iterable<String> addresses,
        Iterable<String> phones, Iterable<String> emails, Iterable<String> urls, String note) {
    StringBuilder newContents = new StringBuilder(100);
    newContents.append("BEGIN:VCARD").append(TERMINATOR);
    newContents.append("VERSION:3.0").append(TERMINATOR);
    StringBuilder newDisplayContents = new StringBuilder(100);
    appendUpToUnique(newContents, newDisplayContents, "N", names, 1, null);
    append(newContents, newDisplayContents, "ORG", organization);
    appendUpToUnique(newContents, newDisplayContents, "ADR", addresses, 1, null);
    appendUpToUnique(newContents, newDisplayContents, "TEL", phones, Integer.MAX_VALUE,
            new Formatter() {
                @Override
                public String format(String source) {
                    return PhoneNumberUtils.formatNumber(source);
                }
            });
    appendUpToUnique(newContents, newDisplayContents, "EMAIL", emails, Integer.MAX_VALUE, null);
    appendUpToUnique(newContents, newDisplayContents, "URL", urls, Integer.MAX_VALUE, null);
    append(newContents, newDisplayContents, "NOTE", note);
    newContents.append("END:VCARD").append(TERMINATOR);
    return new String[] { newContents.toString(), newDisplayContents.toString() };
}
 
Example 2
Source Project: android_9.0.0_r45   Source File: Linkify.java    License: Apache License 2.0 6 votes vote down vote up
private static void gatherTelLinks(ArrayList<LinkSpec> links, Spannable s,
        @Nullable Context context) {
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    final TelephonyManager tm = (context == null)
            ? TelephonyManager.getDefault()
            : TelephonyManager.from(context);
    Iterable<PhoneNumberMatch> matches = phoneUtil.findNumbers(s.toString(),
            tm.getSimCountryIso().toUpperCase(Locale.US),
            Leniency.POSSIBLE, Long.MAX_VALUE);
    for (PhoneNumberMatch match : matches) {
        LinkSpec spec = new LinkSpec();
        spec.url = "tel:" + PhoneNumberUtils.normalizeNumber(match.rawString());
        spec.start = match.start();
        spec.end = match.end();
        links.add(spec);
    }
}
 
Example 3
Source Project: android_9.0.0_r45   Source File: CallLog.java    License: Apache License 2.0 6 votes vote down vote up
private static void updateNormalizedNumber(Context context, ContentResolver resolver,
        String dataId, String number) {
    if (TextUtils.isEmpty(number) || TextUtils.isEmpty(dataId)) {
        return;
    }
    final String countryIso = getCurrentCountryIso(context);
    if (TextUtils.isEmpty(countryIso)) {
        return;
    }
    final String normalizedNumber = PhoneNumberUtils.formatNumberToE164(number,
            getCurrentCountryIso(context));
    if (TextUtils.isEmpty(normalizedNumber)) {
        return;
    }
    final ContentValues values = new ContentValues();
    values.put(Phone.NORMALIZED_NUMBER, normalizedNumber);
    resolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[] {dataId});
}
 
Example 4
Source Project: BaldPhone   Source File: SingleContactActivity.java    License: Apache License 2.0 6 votes vote down vote up
private void inflateWhatsapp() {
    final List<String> whatappNumbers = contact.getWhatsappNumbers();
    for (String whatappNumber : whatappNumbers) {
        final View layout = layoutInflater.inflate(R.layout.contact_whatsapp, ll, false);
        layout.findViewById(R.id.whatsapp).setOnClickListener((v) ->
                startActivity(
                        new Intent("android.intent.activate.MAIN")
                                .setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"))
                                .putExtra("jid",
                                        PhoneNumberUtils.stripSeparators(
                                                whatappNumber
                                                        .replaceAll(
                                                                "[^0123456789]",
                                                                "")
                                        ) + "@s.whatsapp.net")
                )
        );
        ll.addView(layout);
    }
}
 
Example 5
Source Project: BaldPhone   Source File: ShareActivity.java    License: Apache License 2.0 6 votes vote down vote up
public void whatsappShare(String lookupKey) {
    final Contact contact;
    try {
        contact = Contact.fromLookupKey(lookupKey, contentResolver);
    } catch (Contact.ContactNotFoundException e) {
        Log.e(TAG, S.str(e.getMessage()));
        e.printStackTrace();
        BaldToast.error(this);
        finish();
        return;
    }
    shareIntent.setPackage(D.WHATSAPP_PACKAGE_NAME);
    String smsNumber = PhoneNumberUtils.stripSeparators(contact.getWhatsappNumbers().get(0)).replace("+", "").replace(" ", "");
    shareIntent.putExtra("jid", smsNumber + "@s.whatsapp.net"); //phone number without "+" prefix
    startActivity(shareIntent);
    finish();
}
 
Example 6
Source Project: xDrip   Source File: IncomingCallsReceiver.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static String bestPhoneNumberFormatter(final String number) {
    if (number == null) return null;
    final String formatted = PhoneNumberUtils.formatNumber(number);
    if (formatted.contains(" ")) {
        return formatted;
    } else {
        final StringBuilder spaced = new StringBuilder();
        final char[] array = number.toCharArray();
        boolean first = true;
        int counter = 0;
        for (char c : array) {
            spaced.append(c);
            first = false;
            counter++;
            if (counter == 5) {
                spaced.append(" ");
            }
        }
        return spaced.toString();
    }
}
 
Example 7
private static String bestPhoneNumberFormatter(final String number) {
    if (number == null) return null;
    final String formatted = PhoneNumberUtils.formatNumber(number);
    if (formatted.contains(" ")) {
        return formatted;
    } else {
        final StringBuilder spaced = new StringBuilder();
        final char[] array = number.toCharArray();
        boolean first = true;
        int counter = 0;
        for (char c : array) {
            spaced.append(c);
            first = false;
            counter++;
            if (counter == 5) {
                spaced.append(" ");
            }
        }
        return spaced.toString();
    }
}
 
Example 8
Source Project: Android-Commons   Source File: Social.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Normalizes the specified phone number to its E.164 representation, if supported by the platform
 *
 * @param context a context reference
 * @param phoneNumber the phone number to normalize
 * @return the normalized phone number
 */
@SuppressLint("NewApi")
public static String normalizePhoneNumber(final Context context, final String phoneNumber) {
	if (Build.VERSION.SDK_INT >= 21) {
		final String countryIso2 = DeviceInfo.getCountryISO2(context);

		if (countryIso2 != null) {
			final String formatted = PhoneNumberUtils.formatNumberToE164(phoneNumber, countryIso2.toUpperCase(Locale.US));

			if (formatted != null) {
				return formatted;
			}
		}
	}

	return phoneNumber;
}
 
Example 9
Source Project: reacteu-app   Source File: VCardContactEncoder.java    License: MIT License 6 votes vote down vote up
@Override
public String[] encode(Iterable<String> names,
                       String organization,
                       Iterable<String> addresses,
                       Iterable<String> phones,
                       Iterable<String> emails,
                       String url,
                       String note) {
  StringBuilder newContents = new StringBuilder(100);
  StringBuilder newDisplayContents = new StringBuilder(100);
  newContents.append("BEGIN:VCARD").append(TERMINATOR);
  appendUpToUnique(newContents, newDisplayContents, "N", names, 1, null);
  append(newContents, newDisplayContents, "ORG", organization);
  appendUpToUnique(newContents, newDisplayContents, "ADR", addresses, 1, null);
  appendUpToUnique(newContents, newDisplayContents, "TEL", phones, Integer.MAX_VALUE, new Formatter() {
    @Override
    public String format(String source) {
      return PhoneNumberUtils.formatNumber(source);
    }
  });
  appendUpToUnique(newContents, newDisplayContents, "EMAIL", emails, Integer.MAX_VALUE, null);
  append(newContents, newDisplayContents, "URL", url);
  append(newContents, newDisplayContents, "NOTE", note);
  newContents.append("END:VCARD").append(TERMINATOR);
  return new String[] { newContents.toString(), newDisplayContents.toString() };
}
 
Example 10
private boolean isValidAddress(String number, boolean isMms) {
    /*if (isMms) {
        return MessageUtils.isValidMmsAddress(number);
    } else {*/
        // TODO: PhoneNumberUtils.isWellFormedSmsAddress() only check if the number is a valid
        // GSM SMS address. If the address contains a dialable char, it considers it a well
        // formed SMS addr. CDMA doesn't work that way and has a different parser for SMS
        // address (see CdmaSmsAddress.parse(String address)). We should definitely fix this!!!
    return PhoneNumberUtils.isWellFormedSmsAddress(number);
}
 
Example 11
private static String parseRecipient(String recipient) throws RecipientFormattingException {
  recipient = recipient.trim();

  if ((recipient.indexOf('<') != -1) && (recipient.indexOf('>') != -1))
    return parseBracketedNumber(recipient);

  if (PhoneNumberUtils.isWellFormedSmsAddress(recipient))
    return recipient;

  throw new RecipientFormattingException("Recipient: " + recipient + " is badly formatted.");
}
 
Example 12
public static String formatNameAndNumber(String name, String number) {
  // Format like this: Mike Cleron <(650) 555-1234>
  //                   Erick Tseng <(650) 555-1212>
  //                   Tutankhamun <[email protected]>
  //                   (408) 555-1289
  String formattedNumber = PhoneNumberUtils.formatNumber(number);
  if (!TextUtils.isEmpty(name) && !name.equals(number)) {
    return name + " <" + formattedNumber + ">";
  } else {
    return formattedNumber;
  }
}
 
Example 13
Source Project: NettyChat   Source File: StringUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取较纯净的手机号码<br />
 * 删除前缀、空格等
 *
 * @param phone
 * @return
 */
public static String getValidPhoneNumber(String phone) {
	if (phone == null)
		return "";
	if (phone.startsWith("0086")) {
		phone = phone.substring(4);
	}
	if (phone.startsWith("+86")) {
		phone = phone.substring(3);
	}
	PhoneNumberUtils.stripSeparators(phone);
	phone = phone.replace("-", "").replace(" ", "").trim();
	return phone;
}
 
Example 14
Source Project: bcm-android   Source File: RecipientsEditor.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean isValidAddress(String number, boolean isMms) {
    /*if (isMms) {
        return MessageUtils.isValidMmsAddress(number);
    } else {*/
        // TODO: PhoneNumberUtils.isWellFormedSmsAddress() only check if the number is a valid
        // GSM SMS address. If the address contains a dialable char, it considers it a well
        // formed SMS addr. CDMA doesn't work that way and has a different parser for SMS
        // address (see CdmaSmsAddress.parse(String address)). We should definitely fix this!!!
    return PhoneNumberUtils.isWellFormedSmsAddress(number);
}
 
Example 15
Source Project: reacteu-app   Source File: SMSResultHandler.java    License: MIT License 5 votes vote down vote up
@Override
public CharSequence getDisplayContents() {
  SMSParsedResult smsResult = (SMSParsedResult) getResult();
  StringBuilder contents = new StringBuilder(50);
  String[] rawNumbers = smsResult.getNumbers();
  String[] formattedNumbers = new String[rawNumbers.length];
  for (int i = 0; i < rawNumbers.length; i++) {
    formattedNumbers[i] = PhoneNumberUtils.formatNumber(rawNumbers[i]);
  }
  ParsedResult.maybeAppend(formattedNumbers, contents);
  ParsedResult.maybeAppend(smsResult.getSubject(), contents);
  ParsedResult.maybeAppend(smsResult.getBody(), contents);
  return contents.toString();
}
 
Example 16
private static String parseRecipient(String recipient) throws RecipientFormattingException {
  recipient = recipient.trim();

  if ((recipient.indexOf('<') != -1) && (recipient.indexOf('>') != -1))
    return parseBracketedNumber(recipient);

  if (PhoneNumberUtils.isWellFormedSmsAddress(recipient))
    return recipient;

  throw new RecipientFormattingException("Recipient: " + recipient + " is badly formatted.");
}
 
Example 17
public static String formatNameAndNumber(String name, String number) {
  // Format like this: Mike Cleron <(650) 555-1234>
  //                   Erick Tseng <(650) 555-1212>
  //                   Tutankhamun <[email protected]>
  //                   (408) 555-1289
  String formattedNumber = PhoneNumberUtils.formatNumber(number);
  if (!TextUtils.isEmpty(name) && !name.equals(number)) {
    return name + " <" + formattedNumber + ">";
  } else {
    return formattedNumber;
  }
}
 
Example 18
@Override
 public final CharSequence convertToString(Cursor cursor) {
 	CharSequence number = ContactsWrapper.getInstance().transformToSipUri(mContext, cursor);
     boolean isExternalPhone = ContactsWrapper.getInstance().isExternalPhoneNumber(mContext, cursor);
 	if(!TextUtils.isEmpty(number) && isExternalPhone) {
 	    String stripNbr = PhoneNumberUtils.stripSeparators(number.toString());
return Filter.rewritePhoneNumber(mContext, currentAccId, stripNbr);
 	}
 	return number;
 }
 
Example 19
private boolean equalNumbers(String number1, String number2) {
//        if (PhoneNumberUtils.isUriNumber(number1) || PhoneNumberUtils.isUriNumber(number2)) {
//            return compareSipAddresses(number1, number2);
//        } else {
        // Optim -- first try to compare very simply
        if(number1 != null && number2 != null && number1.equals(number2)) {
            return true;
        }
        return PhoneNumberUtils.compare(number1, number2);
//        }
    }
 
Example 20
Source Project: DumbphoneAssistant   Source File: Contact.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
    if(!(o instanceof Contact)) {
        return false;
    }
    return PhoneNumberUtils.compare(number, ((Contact) o).number);
}
 
Example 21
@Override
public CharSequence format(CharSequence value, int index) {
  value = PhoneNumberUtils.formatNumber(value.toString());
  Map<String,Set<String>> metadata =
      metadataForIndex == null || metadataForIndex.size() <= index ? null : metadataForIndex.get(index);
  value = formatMetadata(value, metadata);
  return value;
}
 
Example 22
Source Project: ZXing-Standalone-library   Source File: SMSResultHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence getDisplayContents() {
  SMSParsedResult smsResult = (SMSParsedResult) getResult();
  String[] rawNumbers = smsResult.getNumbers();
  String[] formattedNumbers = new String[rawNumbers.length];
  for (int i = 0; i < rawNumbers.length; i++) {
    formattedNumbers[i] = PhoneNumberUtils.formatNumber(rawNumbers[i]);
  }
  StringBuilder contents = new StringBuilder(50);
  ParsedResult.maybeAppend(formattedNumbers, contents);
  ParsedResult.maybeAppend(smsResult.getSubject(), contents);
  ParsedResult.maybeAppend(smsResult.getBody(), contents);
  return contents.toString();
}
 
Example 23
Source Project: ZXing-Orient   Source File: VCardTelDisplayFormatter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence format(CharSequence value, int index) {
  value = PhoneNumberUtils.formatNumber(value.toString());
  Map<String,Set<String>> metadata =
      metadataForIndex == null || metadataForIndex.size() <= index ? null : metadataForIndex.get(index);
  value = formatMetadata(value, metadata);
  return value;
}
 
Example 24
Source Project: android-nfc-lib   Source File: NfcMessageUtilityImpl.java    License: MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * Precondition :  At least number should not be null
 */
@Override
public NdefMessage createSms(@NotNull String number, String message) throws FormatException {
    number = number.startsWith("+") ? "+" + number.replaceAll("\\D", "") : number.replaceAll("\\D", "");
    if (!PhoneNumberUtils.isGlobalPhoneNumber((number))) {
        throw new FormatException();
    }
    String smsPattern = "sms:" + number + "?body=" + message;
    //String externalType = "nfclab.com:smsService";
    return createUriMessage(smsPattern, NfcPayloadHeader.CUSTOM_SCHEME);
}
 
Example 25
/**
 * Generate the formatted number by ignoring all non-dialable chars and stick the cursor to the
 * nearest dialable char to the left. For instance, if the number is  (650) 123-45678 and '4' is
 * removed then the cursor should be behind '3' instead of '-'.
 */
private String reformat(CharSequence s, int cursor) {
    // The index of char to the leftward of the cursor.
    int curIndex = cursor - 1;
    String formatted = null;
    mFormatter.clear();
    char lastNonSeparator = 0;
    boolean hasCursor = false;
    int len = s.length();
    for (int i = 0; i < len; i++) {
        char c = s.charAt(i);
        if (PhoneNumberUtils.isNonSeparator(c)) {
            if (lastNonSeparator != 0) {
                formatted = getFormattedNumber(lastNonSeparator, hasCursor);
                hasCursor = false;
            }
            lastNonSeparator = c;
        }
        if (i == curIndex) {
            hasCursor = true;
        }
    }
    if (lastNonSeparator != 0) {
        formatted = getFormattedNumber(lastNonSeparator, hasCursor);
    }
    return formatted;
}
 
Example 26
@Override
public CharSequence getDisplayContents() {
  SMSParsedResult smsResult = (SMSParsedResult) getResult();
  String[] rawNumbers = smsResult.getNumbers();
  String[] formattedNumbers = new String[rawNumbers.length];
  for (int i = 0; i < rawNumbers.length; i++) {
    formattedNumbers[i] = PhoneNumberUtils.formatNumber(rawNumbers[i]);
  }
  StringBuilder contents = new StringBuilder(50);
  ParsedResult.maybeAppend(formattedNumbers, contents);
  ParsedResult.maybeAppend(smsResult.getSubject(), contents);
  ParsedResult.maybeAppend(smsResult.getBody(), contents);
  return contents.toString();
}
 
Example 27
@Override
public CharSequence getDisplayContents() {
    SMSParsedResult smsResult = (SMSParsedResult) getResult();
    StringBuilder contents = new StringBuilder(50);
    String[] rawNumbers = smsResult.getNumbers();
    String[] formattedNumbers = new String[rawNumbers.length];
    for (int i = 0; i < rawNumbers.length; i++) {
        formattedNumbers[i] = PhoneNumberUtils.formatNumber(rawNumbers[i]);
    }
    ParsedResult.maybeAppend(formattedNumbers, contents);
    ParsedResult.maybeAppend(smsResult.getSubject(), contents);
    ParsedResult.maybeAppend(smsResult.getBody(), contents);
    return contents.toString();
}
 
Example 28
/**
     * updates hint
     */
    private void updateHint() {
        if (editText_registeredCarrierNumber != null && hintExampleNumberEnabled) {
            String formattedNumber = "";
            Phonenumber.PhoneNumber exampleNumber = getPhoneUtil().getExampleNumberForType(getSelectedCountryNameCode(), getSelectedHintNumberType());
            if (exampleNumber != null) {
                formattedNumber = exampleNumber.getNationalNumber() + "";
//                Log.d(TAG, "updateHint: " + formattedNumber);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    formattedNumber = PhoneNumberUtils.formatNumber(getSelectedCountryCodeWithPlus() + formattedNumber, getSelectedCountryNameCode());
                } else {
                    formattedNumber = PhoneNumberUtils.formatNumber(getSelectedCountryCodeWithPlus() + formattedNumber);
                }
                if (formattedNumber != null) {
                    formattedNumber = formattedNumber.substring(getSelectedCountryCodeWithPlus().length()).trim();
                }
//                Log.d(TAG, "updateHint: after format " + formattedNumber + " " + selectionMemoryTag);
            } else {
//                Log.w(TAG, "updateHint: No example number found for this country (" + getSelectedCountryNameCode() + ") or this type (" + hintExampleNumberType.name() + ").");
            }

            //fallback to original hint
            if (formattedNumber == null) {
                formattedNumber = originalHint;
            }

            editText_registeredCarrierNumber.setHint(formattedNumber);
        }
    }
 
Example 29
private boolean hasSeparator(final CharSequence s, final int start, final int count) {
    for (int i = start; i < start + count; i++) {
        char c = s.charAt(i);
        if (!PhoneNumberUtils.isNonSeparator(c)) {
            return true;
        }
    }
    return false;
}
 
Example 30
Source Project: weex   Source File: VCardTelDisplayFormatter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence format(CharSequence value, int index) {
  value = PhoneNumberUtils.formatNumber(value.toString());
  Map<String,Set<String>> metadata =
      metadataForIndex == null || metadataForIndex.size() <= index ? null : metadataForIndex.get(index);
  value = formatMetadata(value, metadata);
  return value;
}