@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; }
/** * 调起系统打电话功能 */ public void doCallPhoneTo(String phoneNumber) { if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) { if (mayCallPhone()) { Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNumber)); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } startActivity(intent); } } }
/** * For a given address type, extract the recipients from the headers. * * @param addressType can be PduHeaders.FROM or PduHeaders.TO * @param recipients a HashSet that is loaded with the recipients from the FROM or TO headers * @param addressMap a HashMap of the addresses from the ADDRESS_FIELDS header * @param excludeMyNumber if true, the number of this phone will be excluded from recipients */ private void loadRecipients(int addressType, HashSet<String> recipients, HashMap<Integer, EncodedStringValue[]> addressMap, boolean excludeMyNumber) { EncodedStringValue[] array = addressMap.get(addressType); if (array == null) { return; } // If the TO recipients is only a single address, then we can skip loadRecipients when // we're excluding our own number because we know that address is our own. if (excludeMyNumber && array.length == 1) { return; } String myNumber = excludeMyNumber ? mTelephonyManager.getLine1Number() : null; for (EncodedStringValue v : array) { if (v != null) { String number = v.getString(); if ((myNumber == null || !PhoneNumberUtils.compare(number, myNumber)) && !recipients.contains(number)) { // Only add numbers which aren't my own number. recipients.add(number); } } } }
/** * Formats address to normal form like +[country][prefix][localnumber] * @param address * @return */ private static String getNormalizedAddress(String address) { String number=stripAddress(address); try { //parse number using current locale rules Phonenumber.PhoneNumber phonenumber=phoneNumberUtil.parseAndKeepRawInput(number, Locale.getDefault().getCountry()); //Phonenumber.PhoneNumber phonenumber = phoneNumberUtil.parse(number, Locale.getDefault().getCountry()); //format to international form //phoneNumberUtil number=phoneNumberUtil.format(phonenumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL); //stripe any formatting symbols return stripAddress(number); } catch(Exception ex) { //in case of fail use default formatting rules number=PhoneNumberUtils.formatNumber(number); //stripe any formatting symbols return stripAddress(number); } }
private void enterState(int state) { switch(state) { case LOADING: mActionBar.setTitle(R.string.bt_card_details); mViewSwitcher.setDisplayedChild(0); break; case CARD_ENTRY: mActionBar.setTitle(R.string.bt_card_details); mAddCardView.setVisibility(VISIBLE); break; case DETAILS_ENTRY: mActionBar.setTitle(R.string.bt_card_details); mEditCardView.setCardNumber(mAddCardView.getCardForm().getCardNumber()); mEditCardView.useUnionPay(this, mUnionPayCard, mUnionPayDebitCard); mEditCardView.setVisibility(VISIBLE); break; case ENROLLMENT_ENTRY: mActionBar.setTitle(R.string.bt_confirm_enrollment); mEnrollmentCardView.setPhoneNumber( PhoneNumberUtils.formatNumber(mEditCardView.getCardForm().getCountryCode() + mEditCardView.getCardForm().getMobileNumber())); mEnrollmentCardView.setVisibility(VISIBLE); break; } }
private void retrieveFiles(){ RealmResults<CallHistory> result = myRealm.where(CallHistory.class) .isNotNull(CallHistory.kCOL_FILE_PATH) .findAllSorted(CallHistory.kCOL_DATE_TIME, Sort.DESCENDING); arrayFilePaths.clear(); arrayCalls.clear(); if (result.size() > 0) { for(CallHistory c:result) { arrayFilePaths.add(PhoneNumberUtils.formatNumber(c.phoneNumber) + " " + getDate(c.dateTime, "d/MM/yyyy HH:mm:ss")); arrayCalls.add(c); } } if (adapter != null) { adapter.notifyDataSetChanged(); if (arrayCalls.size() > 0 && !hasPlayerSetup){ AudioWife.getInstance().init(CallReceiverActivity.this, Uri.parse(arrayCalls.get(0).getFilePath())).useDefaultUi(llMediaPlayer, getLayoutInflater()); hasPlayerSetup = true; } } }
/** * This function combines selected country code from CCP and carrier number from @param editTextCarrierNumber * This will return formatted number. * * @return Full number is countryCode + carrierNumber i.e countryCode= 91 and carrier number= 8866667722, this will return "918866667722" */ public String getFormattedFullNumber() { String formattedFullNumber; Phonenumber.PhoneNumber phoneNumber; if (editText_registeredCarrierNumber != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { formattedFullNumber = PhoneNumberUtils.formatNumber(getFullNumberWithPlus(), getSelectedCountryCode()); } else { formattedFullNumber = PhoneNumberUtils.formatNumber(getFullNumberWithPlus()); } } else { formattedFullNumber = getSelectedCountry().getPhoneCode(); Log.w(TAG, "EditText for carrier number is not registered. Register it using registerCarrierNumberEditText() before getFullNumber() or setFullNumber()."); } return formattedFullNumber; }
@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() }; }
@Nullable private static ListIterator<User> getUserPosition(Context context, User user) { ArrayList<User> users = getUsers(context); if (users != null) { ListIterator<User> iterator; iterator = users.listIterator(); while (iterator.hasNext()) { if (PhoneNumberUtils.compare(iterator.next().number, user.number)) { return iterator; } } } return null; }
@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() }; }
@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(); }
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); }
@VisibleForTesting static boolean isNumberAddress(@NonNull String number) { if (number.contains("@")) return false; if (GroupUtil.isEncodedGroup(number)) return false; final String networkNumber = PhoneNumberUtils.extractNetworkPortion(number); if (TextUtils.isEmpty(networkNumber)) return false; if (networkNumber.length() < 3) return false; return PhoneNumberUtils.isWellFormedSmsAddress(number); }
protected long insertMessageOutbox(long threadId, OutgoingTextMessage message, long type, boolean forceSms, long date) { if (message.isKeyExchange()) type |= Types.KEY_EXCHANGE_BIT; else if (message.isSecureMessage()) type |= (Types.SECURE_MESSAGE_BIT | Types.PUSH_MESSAGE_BIT); else if (message.isEndSession()) type |= Types.END_SESSION_BIT; if (forceSms) type |= Types.MESSAGE_FORCE_SMS_BIT; String address = message.getRecipients().getPrimaryRecipient().getNumber(); ContentValues contentValues = new ContentValues(6); contentValues.put(ADDRESS, PhoneNumberUtils.formatNumber(address)); contentValues.put(THREAD_ID, threadId); contentValues.put(BODY, message.getMessageBody()); contentValues.put(DATE_RECEIVED, System.currentTimeMillis()); contentValues.put(DATE_SENT, date); contentValues.put(READ, 1); contentValues.put(TYPE, type); contentValues.put(SUBSCRIPTION_ID, message.getSubscriptionId()); contentValues.put(EXPIRES_IN, message.getExpiresIn()); try { contentValues.put(RECEIPT_COUNT, earlyReceiptCache.remove(date, canonicalizeNumber(context, address))); } catch (InvalidNumberException e) { Log.w(TAG, e); } SQLiteDatabase db = databaseHelper.getWritableDatabase(); long messageId = db.insert(TABLE_NAME, ADDRESS, contentValues); DatabaseFactory.getThreadDatabase(context).update(threadId, true); DatabaseFactory.getThreadDatabase(context).setLastSeen(threadId); notifyConversationListeners(threadId); jobManager.add(new TrimThreadJob(context, threadId)); return messageId; }
private static String parseBracketedNumber(String recipient) throws RecipientFormattingException { int begin = recipient.indexOf('<'); int end = recipient.indexOf('>'); String value = recipient.substring(begin + 1, end); if (PhoneNumberUtils.isWellFormedSmsAddress(value)) return value; else throw new RecipientFormattingException("Bracketed value: " + value + " is not valid."); }
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."); }
@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; }
private void applyRewritingInfo() { // Rewrite information textView update String newText = digits.getText().toString(); if(accountChooserFilterItem != null && accountChooserFilterItem.isChecked()) { if(isDigit) { newText = PhoneNumberUtils.stripSeparators(newText); } rewriteTextInfo.setText(rewriteNumber(newText)); }else { rewriteTextInfo.setText(""); } }
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); // } }
/** * Checks address completion status in the given profile. * * If the country code is not set or invalid, but all fields for the default locale's country * code are present, then the profile is deemed "complete." AutoflllAddress.toPaymentAddress() * will use the default locale to fill in a blank country code before sending the address to the * renderer. * * @param profile The autofill profile containing the address information. * @return int The completion status. */ @CompletionStatus public static int checkAddressCompletionStatus(AutofillProfile profile) { int invalidFieldsCount = 0; int completionStatus = COMPLETE; if (!PhoneNumberUtils.isGlobalPhoneNumber( PhoneNumberUtils.stripSeparators(profile.getPhoneNumber().toString()))) { completionStatus = INVALID_PHONE_NUMBER; invalidFieldsCount++; } List<Integer> requiredFields = AutofillProfileBridge.getRequiredAddressFields( AutofillAddress.getCountryCode(profile)); for (int fieldId : requiredFields) { if (fieldId == AddressField.RECIPIENT || fieldId == AddressField.COUNTRY) continue; if (!TextUtils.isEmpty(getProfileField(profile, fieldId))) continue; completionStatus = INVALID_ADDRESS; invalidFieldsCount++; break; } if (TextUtils.isEmpty(profile.getFullName())) { completionStatus = INVALID_RECIPIENT; invalidFieldsCount++; } if (invalidFieldsCount > 1) { completionStatus = INVALID_MULTIPLE_FIELDS; } return completionStatus; }
public static String buildNameAndNumber(String name, String number) { // Format like this: Mike Cleron <(650) 555-1234> // Erick Tseng <(650) 555-1212> // (408) 555-1289 if (!TextUtils.isEmpty(name) && !name.equals(number)) { return name + " <" + PhoneNumberUtils.formatNumber(number) + ">"; } else { return PhoneNumberUtils.formatNumber(number); } }
@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; }
/** * 调起系统发短信功能 */ public void doSendSMSTo(String phoneNumber, String message) { if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber)); intent.putExtra("sms_body", message); startActivity(intent); } }
public static boolean isValidPhone(String target) { if (target.equals("")) { return false; } else if(target.length()!=10){ return false; } else { return PhoneNumberUtils.isGlobalPhoneNumber(target); } }
/** * Uses an implicit intent to make the phone call. * Before calling, checks to see if permission is granted. * * @param view View that was clicked. */ public void callNumber(View view) { String normalizedPhoneNumber; // Find the editText_main view and assign it to editText. EditText editText = (EditText) findViewById(R.id.editText_main); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Log.d(TAG, "Running version earlier than Lollipop. Can't normalize number."); normalizedPhoneNumber = editText.getText().toString(); } else { normalizedPhoneNumber = PhoneNumberUtils.normalizeNumber(editText.getText().toString()); } // Use format with "tel:" and phone number to create phoneNumber. String phoneNumber = String.format("tel: %s", normalizedPhoneNumber); // Log the concatenated phone number for dialing. Log.d(TAG, getString(R.string.dial_number) + phoneNumber); Toast.makeText(this, getString(R.string.dial_number) + phoneNumber, Toast.LENGTH_LONG).show(); // Create the intent. Intent callIntent = new Intent(Intent.ACTION_CALL); // Set the data for the intent as the phone number. callIntent.setData(Uri.parse(phoneNumber)); // If package resolves to an app, check for phone permission, // and send intent. if (callIntent.resolveActivity(getPackageManager()) != null) { checkForPhonePermission(); startActivity(callIntent); } else { Log.e(TAG, "Can't resolve app for ACTION_CALL Intent."); } }
public int isContactFilter(Context context, String number) { try { contentResolver = context.getContentResolver(); contentUri = DatabaseProvider.CONTACT_FILTER_CONTENT_URI; Cursor cursor = contentResolver.query(contentUri, null, null, null, CONTACT_FILTER.DEFAULT_SORT_ORDER); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { String contactFilterNumber = cursor.getString(cursor.getColumnIndex(CONTACT_FILTER.NUMBER)); int contactFilterRecordable = cursor.getInt(cursor.getColumnIndex(CONTACT_FILTER.RECORDABLE)); boolean isIdenticalNumber = PhoneNumberUtils.compare(number, contactFilterNumber); if (isIdenticalNumber == true) { return contactFilterRecordable; } } return -1; } catch (Exception e) { Log.w("FiltersManager", "isContactFilter : " + context.getString(R.string.log_preferences_filters_manager_error_is_contact_filter) + " : " + number + " : " + e); databaseManager.insertLog(context, "" + context.getString(R.string.log_preferences_filters_manager_error_is_contact_filter) + " : " + number, new Date().getTime(), 2, false); return -1; } }