Пример #1
0
  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;
    else if (message.isEndSession()) type |= Types.END_SESSION_BIT;
    if (forceSms) type |= Types.MESSAGE_FORCE_SMS_BIT;

    ContentValues contentValues = new ContentValues(6);
    contentValues.put(
        ADDRESS,
        PhoneNumberUtils.formatNumber(message.getRecipients().getPrimaryRecipient().getNumber()));
    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);

    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    long messageId = db.insert(TABLE_NAME, ADDRESS, contentValues);

    DatabaseFactory.getThreadDatabase(context).update(threadId, true);
    notifyConversationListeners(threadId);
    jobManager.add(new TrimThreadJob(context, threadId));

    return messageId;
  }
Пример #2
0
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    addPreferencesFromResource(R.xml.my_phone_number);
    mPhoneNumberStatus = findPreference(KEY_PHONE_NUMBER_STATUS_PREFERENCE);

    mTelephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

    mPhone = PhoneFactory.getDefaultPhone();

    String rawNumber = mTelephonyManager.getLine1Number();
    String formattedNumber = null;

    if (!TextUtils.isEmpty(rawNumber)) {
      formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
    } else {
      formattedNumber = getResources().getString(R.string.unknown);
    }

    mPhoneNumberStatus.setSummary(formattedNumber);

    Log.d(LOG_TAG, " sim state: " + mTelephonyManager.getSimState());

    // Check SIM status
    if (mTelephonyManager.getSimState() != TelephonyManager.SIM_STATE_READY) {
      showNoSimAlertDialog();
    }
  }
Пример #3
0
 public synchronized void setNumber(String number) {
   if (!MessageUtils.isEmailAddress(number)) {
     mNumber =
         PhoneNumberUtils.formatNumber(number, mNumberE164, Locale.getDefault().getCountry());
   } else {
     mNumber = number;
   }
   notSynchronizedUpdateNameAndNumber();
   mNumberIsModified = true;
 }
Пример #4
0
  // SWISTART
  private void updatePhoneType() {
    mPhone = PhoneFactory.getDefaultPhone();
    if (mPhone != null) {
      // NOTE "imei" is the "Device ID" since it represents
      //  the IMEI in GSM and the MEID in CDMA
      if (mPhone.getPhoneName().equals("CDMA")) {
        setSummaryText(KEY_MEID_NUMBER, mPhone.getMeid());
        setSummaryText(KEY_MIN_NUMBER, mPhone.getCdmaMin());
        if (getResources().getBoolean(R.bool.config_msid_enable)) {
          findPreference(KEY_MIN_NUMBER).setTitle(R.string.status_msid_number);
        }
        setSummaryText(KEY_PRL_VERSION, mPhone.getCdmaPrlVersion());
        removePreferenceFromScreen(KEY_IMEI_SV);

        if (mPhone.getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE) {
          // Show ICC ID and IMEI for LTE device
          setSummaryText(KEY_ICC_ID, mPhone.getIccSerialNumber());
          setSummaryText(KEY_IMEI, mPhone.getImei());
        } else {
          // device is not GSM/UMTS, do not display GSM/UMTS features
          // check Null in case no specified preference in overlay xml
          removePreferenceFromScreen(KEY_IMEI);
          removePreferenceFromScreen(KEY_ICC_ID);
        }
      } else {
        setSummaryText(KEY_IMEI, mPhone.getDeviceId());

        setSummaryText(
            KEY_IMEI_SV,
            ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceSoftwareVersion());

        // device is not CDMA, do not display CDMA features
        // check Null in case no specified preference in overlay xml
        removePreferenceFromScreen(KEY_PRL_VERSION);
        removePreferenceFromScreen(KEY_MEID_NUMBER);
        removePreferenceFromScreen(KEY_MIN_NUMBER);
        removePreferenceFromScreen(KEY_ICC_ID);

        // only show area info when SIM country is Brazil
        if ("br".equals(mTelephonyManager.getSimCountryIso())) {
          mShowLatestAreaInfo = true;
        }
      }
      String rawNumber = mPhone.getLine1Number(); // may be null or empty
      String formattedNumber = null;
      if (!TextUtils.isEmpty(rawNumber)) {
        formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
      }
      // If formattedNumber is null or empty, it'll display as "Unknown".
      setSummaryText(KEY_PHONE_NUMBER, formattedNumber);
    }
  }
Пример #5
0
 @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();
 }
  // Overriden so we can hyphenate phone numbers, format birthdays, and bold the name.
  @Override
  public CharSequence getDisplayContents() {
    AddressBookParsedResult result = (AddressBookParsedResult) getResult();
    StringBuilder contents = new StringBuilder(100);
    ParsedResult.maybeAppend(result.getNames(), contents);
    int namesLength = contents.length();

    String pronunciation = result.getPronunciation();
    if (pronunciation != null && !pronunciation.isEmpty()) {
      contents.append("\n(");
      contents.append(pronunciation);
      contents.append(')');
    }

    ParsedResult.maybeAppend(result.getTitle(), contents);
    ParsedResult.maybeAppend(result.getOrg(), contents);
    ParsedResult.maybeAppend(result.getAddresses(), contents);
    String[] numbers = result.getPhoneNumbers();
    if (numbers != null) {
      for (String number : numbers) {
        if (number != null) {
          ParsedResult.maybeAppend(PhoneNumberUtils.formatNumber(number), contents);
        }
      }
    }
    ParsedResult.maybeAppend(result.getEmails(), contents);
    ParsedResult.maybeAppend(result.getURLs(), contents);

    String birthday = result.getBirthday();
    if (birthday != null && !birthday.isEmpty()) {
      Date date = parseDate(birthday);
      if (date != null) {
        ParsedResult.maybeAppend(
            DateFormat.getDateInstance(DateFormat.MEDIUM).format(date.getTime()), contents);
      }
    }
    ParsedResult.maybeAppend(result.getNote(), contents);

    if (namesLength > 0) {
      // Bold the full name to make it stand out a bit.
      Spannable styled = new SpannableString(contents.toString());
      styled.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, namesLength, 0);
      return styled;
    } else {
      return contents.toString();
    }
  }
Пример #7
0
  private void initializeTitleBar() {
    String title = null;
    String subtitle = null;

    if (isSingleConversation()) {
      title = getRecipients().getPrimaryRecipient().getName();

      if (title == null || title.trim().length() == 0) {
        title = getRecipients().getPrimaryRecipient().getNumber();
      } else {
        subtitle = getRecipients().getPrimaryRecipient().getNumber();
      }
    } else if (isGroupConversation()) {
      if (isPushGroupConversation()) {
        final String groupName = getRecipients().getPrimaryRecipient().getName();
        title =
            (!TextUtils.isEmpty(groupName))
                ? groupName
                : getString(R.string.ConversationActivity_unnamed_group);
        final Bitmap avatar = getRecipients().getPrimaryRecipient().getContactPhoto();
        if (avatar != null) {
          getSupportActionBar()
              .setIcon(
                  new BitmapDrawable(getResources(), BitmapUtil.getCircleCroppedBitmap(avatar)));
        }
      } else {
        title = getString(R.string.ConversationActivity_group_conversation);
        int size = getRecipients().getRecipientsList().size();
        subtitle =
            (size == 1)
                ? getString(R.string.ConversationActivity_d_recipients_in_group_singular)
                : String.format(
                    getString(R.string.ConversationActivity_d_recipients_in_group), size);
      }
    } else {
      title = getString(R.string.ConversationActivity_compose_message);
      subtitle = "";
    }

    this.getSupportActionBar().setTitle(title);

    if (subtitle != null && !Util.isEmpty(subtitle))
      this.getSupportActionBar().setSubtitle(PhoneNumberUtils.formatNumber(subtitle));

    this.invalidateOptionsMenu();
  }
Пример #8
0
  /**
   * Fomat the name and number.
   *
   * @param name
   * @param number
   * @param numberE164 the number's E.164 representation, is used to get the country the number
   *     belongs to.
   * @return the formatted name and number
   */
  public static String formatNameAndNumber(String name, String number, String numberE164) {
    // Format like this: Mike Cleron <(650) 555-1234>
    //                   Erick Tseng <(650) 555-1212>
    //                   Tutankhamun <*****@*****.**>
    //                   (408) 555-1289
    String formattedNumber = number;
    if (!MessageUtils.isEmailAddress(number)) {
      formattedNumber =
          PhoneNumberUtils.formatNumber(number, numberE164, Locale.getDefault().getCountry());
    }

    if (!TextUtils.isEmpty(name) && !name.equals(number)) {
      return name + " <" + formattedNumber + ">";
    } else {
      return formattedNumber;
    }
  }
Пример #9
0
  private void updatePreference() {
    if (mPhone.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) {
      // only show area info when SIM country is Brazil
      if ("br".equals(mTelephonyManager.getSimCountryIso(mUtility.getSubId()))) {
        mShowLatestAreaInfo = true;
      }
    }

    String rawNumber = mPhone.getLine1Number(); // may be null or empty
    String formattedNumber = null;
    if (!TextUtils.isEmpty(rawNumber)) {
      formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
    }
    // If formattedNumber is null or empty, it'll display as "Unknown".
    setSummaryText(KEY_PHONE_NUMBER, formattedNumber);

    if (!mShowLatestAreaInfo) {
      removePreferenceFromScreen(KEY_LATEST_AREA_INFO);
    }
  }
  /**
   * Format the given phone number using {@link PhoneNumberUtils#formatNumber(android.text.Editable,
   * int)}. This helper method uses {@link #sEditable} and {@link #sFormattingType} to prevent
   * allocations between multiple calls.
   *
   * <p>Because of the shared {@link #sEditable} builder, <b>this method is not thread safe</b>, and
   * should only be called from the GUI thread.
   *
   * <p>If the given String object is null or empty, return an empty String.
   */
  private String formatPhoneNumber(String number) {
    if (TextUtils.isEmpty(number)) {
      return "";
    }

    // If "number" is really a SIP address, don't try to do any formatting at all.
    if (PhoneNumberUtils.isUriNumber(number)) {
      return number;
    }

    // Cache formatting type if not already present
    if (sFormattingType == FORMATTING_TYPE_INVALID) {
      sFormattingType = PhoneNumberUtils.getFormatTypeForLocale(Locale.getDefault());
    }

    sEditable.clear();
    sEditable.append(number);

    PhoneNumberUtils.formatNumber(sEditable, sFormattingType);
    return sEditable.toString();
  }
Пример #11
0
  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;
    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);
    notifyConversationListeners(threadId);
    jobManager.add(new TrimThreadJob(context, threadId));

    return messageId;
  }
Пример #12
0
 private String formatPhoneNumber(String address) {
   address = URLDecoder.decode(address);
   address = "" + Html.fromHtml(address);
   address = PhoneNumberUtils.formatNumber(address);
   return address;
 }
Пример #13
0
  @Override
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mHandler = new MyHandler(this);

    mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

    addPreferencesFromResource(R.xml.device_info_status);
    mBatteryLevel = findPreference(KEY_BATTERY_LEVEL);
    mBatteryStatus = findPreference(KEY_BATTERY_STATUS);

    mRes = getResources();
    sUnknown = mRes.getString(R.string.device_info_default);
    if (UserHandle.myUserId() == UserHandle.USER_OWNER) {
      mPhone = PhoneFactory.getDefaultPhone();
    }
    // Note - missing in zaku build, be careful later...
    mSignalStrength = findPreference(KEY_SIGNAL_STRENGTH);
    mUptime = findPreference("up_time");

    if (mPhone == null || Utils.isWifiOnly(getApplicationContext())) {
      for (String key : PHONE_RELATED_ENTRIES) {
        removePreferenceFromScreen(key);
      }
    } else {
      // NOTE "imei" is the "Device ID" since it represents
      //  the IMEI in GSM and the MEID in CDMA
      if (mPhone.getPhoneName().equals("CDMA")) {
        setSummaryText(KEY_MEID_NUMBER, mPhone.getMeid());
        setSummaryText(KEY_MIN_NUMBER, mPhone.getCdmaMin());
        if (getResources().getBoolean(R.bool.config_msid_enable)) {
          findPreference(KEY_MIN_NUMBER).setTitle(R.string.status_msid_number);
        }
        setSummaryText(KEY_PRL_VERSION, mPhone.getCdmaPrlVersion());
        removePreferenceFromScreen(KEY_IMEI_SV);

        if (mPhone.getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE) {
          // Show ICC ID and IMEI for LTE device
          setSummaryText(KEY_ICC_ID, mPhone.getIccSerialNumber());
          setSummaryText(KEY_IMEI, mPhone.getImei());
        } else {
          // device is not GSM/UMTS, do not display GSM/UMTS features
          // check Null in case no specified preference in overlay xml
          removePreferenceFromScreen(KEY_IMEI);
          removePreferenceFromScreen(KEY_ICC_ID);
        }
      } else {
        setSummaryText(KEY_IMEI, mPhone.getDeviceId());

        setSummaryText(
            KEY_IMEI_SV,
            ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceSoftwareVersion());

        // device is not CDMA, do not display CDMA features
        // check Null in case no specified preference in overlay xml
        removePreferenceFromScreen(KEY_PRL_VERSION);
        removePreferenceFromScreen(KEY_MEID_NUMBER);
        removePreferenceFromScreen(KEY_MIN_NUMBER);
        removePreferenceFromScreen(KEY_ICC_ID);

        // only show area info when SIM country is Brazil
        if ("br".equals(mTelephonyManager.getSimCountryIso())) {
          mShowLatestAreaInfo = true;
        }
      }

      String rawNumber = mPhone.getLine1Number(); // may be null or empty
      String formattedNumber = null;
      if (!TextUtils.isEmpty(rawNumber)) {
        formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
      }
      // If formattedNumber is null or empty, it'll display as "Unknown".
      setSummaryText(KEY_PHONE_NUMBER, formattedNumber);

      mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
      mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
      mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);

      if (!mShowLatestAreaInfo) {
        removePreferenceFromScreen(KEY_LATEST_AREA_INFO);
      }
    }

    setWimaxStatus();
    setWifiStatus();
    setBtStatus();
    setIpAddressStatus();

    String serial = Build.SERIAL;
    if (serial != null && !serial.equals("")) {
      setSummaryText(KEY_SERIAL_NUMBER, serial);
    } else {
      removePreferenceFromScreen(KEY_SERIAL_NUMBER);
    }
  }
    @Override
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
      try {
        if (this != mQueryHandler) {
          Log.d(TAG, "onQueryComplete: discard result, the query handler is reset!");
          return;
        }
        if (ConfirmAddDetailActivity.this.isFinishing()) {
          return;
        }

        switch (token) {
          case TOKEN_PHOTO_QUERY:
            {
              // Set the photo
              Bitmap photoBitmap = null;
              if (cursor != null && cursor.moveToFirst() && !cursor.isNull(PhotoQuery.PHOTO)) {
                byte[] photoData = cursor.getBlob(PhotoQuery.PHOTO);
                photoBitmap = BitmapFactory.decodeByteArray(photoData, 0, photoData.length, null);
              }

              if (photoBitmap != null) {
                mPhotoView.setImageBitmap(photoBitmap);
              }

              break;
            }
          case TOKEN_CONTACT_INFO:
            {
              // Set the contact's name
              if (cursor != null && cursor.moveToFirst()) {
                // Get the cursor values
                mDisplayName = cursor.getString(ContactQuery.DISPLAY_NAME);
                final long photoId = cursor.getLong(ContactQuery.PHOTO_ID);

                // If there is no photo ID, then do a disambiguation
                // query because other contacts could have the same
                // name as this contact.
                if (photoId == 0) {
                  mContactId = cursor.getLong(ContactQuery._ID);
                  startDisambiguationQuery(mDisplayName);
                } else {
                  // Otherwise do the photo query.
                  Uri lookupUri =
                      Contacts.getLookupUri(mContactId, cursor.getString(ContactQuery.LOOKUP_KEY));
                  startPhotoQuery(photoId, lookupUri);
                  // Display the name because there is no
                  // disambiguation query.
                  setDisplayName();
                  showDialogContent();
                }
              }
              break;
            }
          case TOKEN_DISAMBIGUATION_QUERY:
            {
              // If a cursor was returned with more than 0 results,
              // then at least one other contact exists with the same
              // name as this contact. Extra info on this contact must
              // be displayed to disambiguate the contact, so retrieve
              // those additional fields. Otherwise, no other contacts
              // with this name exists, so do nothing further.
              if (cursor != null && cursor.getCount() > 0) {
                startExtraInfoQuery();
              } else {
                // If there are no other contacts with this name,
                // then display the name.
                setDisplayName();
                showDialogContent();
              }
              break;
            }
          case TOKEN_EXTRA_INFO_QUERY:
            {
              // This case should only occur if there are one or more
              // other contacts with the same contact name.
              if (cursor != null && cursor.moveToFirst()) {
                HashMap<String, String> hashMapCursorData = new HashMap<String, String>();

                // Convert the cursor data into a hashmap of
                // (mimetype, data value) pairs. If a contact has
                // multiple values with the same mimetype, it's fine
                // to override that hashmap entry because we only
                // need one value of that type.
                while (!cursor.isAfterLast()) {
                  final String mimeType = cursor.getString(ExtraInfoQuery.MIMETYPE);
                  if (!TextUtils.isEmpty(mimeType)) {
                    String value = cursor.getString(ExtraInfoQuery.DATA1);
                    if (!TextUtils.isEmpty(value)) {
                      // As a special case, phone numbers
                      // should be formatted in a specific way.
                      if (Phone.CONTENT_ITEM_TYPE.equals(mimeType)) {
                        value = PhoneNumberUtils.formatNumber(value);
                      }
                      hashMapCursorData.put(mimeType, value);
                    }
                  }
                  cursor.moveToNext();
                }

                // Find the first non-empty field according to the
                // mimetype priority list and display this under the
                // contact's display name to disambiguate the contact.
                for (String mimeType : MIME_TYPE_PRIORITY_LIST) {
                  if (hashMapCursorData.containsKey(mimeType)) {
                    setDisplayName();
                    setExtraInfoField(hashMapCursorData.get(mimeType));
                    break;
                  }
                }
                showDialogContent();
              }
              break;
            }
        }
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }
    }
Пример #15
0
 protected String getP(JSONObject Obj, String Name) {
   String Phone = getS(Obj, Name);
   return PhoneNumberUtils.formatNumber(Phone);
 }
 // Overriden so we can take advantage of Android's phone number hyphenation routines.
 @Override
 public CharSequence getDisplayContents() {
   String contents = getResult().getDisplayResult();
   contents = contents.replace("\r", "");
   return PhoneNumberUtils.formatNumber(contents);
 }
    /**
     * Overrides onQueryComplete from AsyncQueryHandler.
     *
     * <p>This method takes into account the state of this class; we construct the CallerInfo object
     * only once for each set of listeners. When the query thread has done its work and calls this
     * method, we inform the remaining listeners in the queue, until we're out of listeners. Once we
     * get the message indicating that we should expect no new listeners for this CallerInfo object,
     * we release the AsyncCursorInfo back into the pool.
     */
    @Override
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
      if (DBG) log("query complete for token: " + token);

      // get the cookie and notify the listener.
      CookieWrapper cw = (CookieWrapper) cookie;
      if (cw == null) {
        // Normally, this should never be the case for calls originating
        // from within this code.
        // However, if there is any code that calls this method, we should
        // check the parameters to make sure they're viable.
        if (DBG) log("Cookie is null, ignoring onQueryComplete() request.");
        return;
      }

      if (cw.event == EVENT_END_OF_QUEUE) {
        release();
        return;
      }

      // check the token and if needed, create the callerinfo object.
      if (mCallerInfo == null) {
        if ((mQueryContext == null) || (mQueryUri == null)) {
          throw new QueryPoolException(
              "Bad context or query uri, or CallerInfoAsyncQuery already released.");
        }

        // adjust the callerInfo data as needed, and only if it was set from the
        // initial query request.
        // Change the callerInfo number ONLY if it is an emergency number or the
        // voicemail number, and adjust other data (including photoResource)
        // accordingly.
        if (cw.event == EVENT_EMERGENCY_NUMBER) {
          // Note we're setting the phone number here (refer to javadoc
          // comments at the top of CallerInfo class).
          mCallerInfo = new CallerInfo().markAsEmergency(mQueryContext);
        } else if (cw.event == EVENT_VOICEMAIL_NUMBER) {
          mCallerInfo = new CallerInfo().markAsVoiceMail();
        } else {
          mCallerInfo = CallerInfo.getCallerInfo(mQueryContext, mQueryUri, cursor);
          // Use the number entered by the user for display.
          if (!TextUtils.isEmpty(cw.number)) {
            mCallerInfo.phoneNumber = PhoneNumberUtils.formatNumber(cw.number);
          }
        }

        if (DBG) log("constructing CallerInfo object for token: " + token);

        // notify that we can clean up the queue after this.
        CookieWrapper endMarker = new CookieWrapper();
        endMarker.event = EVENT_END_OF_QUEUE;
        startQuery(token, endMarker, null, null, null, null, null);
      }

      // notify the listener that the query is complete.
      if (cw.listener != null) {
        if (DBG)
          log(
              "notifying listener: "
                  + cw.listener.getClass().toString()
                  + " for token: "
                  + token
                  + mCallerInfo);
        cw.listener.onQueryComplete(token, cw.cookie, mCallerInfo);
      }
    }
Пример #18
0
  private void encodeQRCodeContents(Intent intent, String type) {
    switch (type) {
      case Contents.Type.TEXT:
        String textData = intent.getStringExtra(Intents.Encode.DATA);
        if (textData != null && !textData.isEmpty()) {
          contents = textData;
          displayContents = textData;
          title = activity.getString(R.string.contents_text);
        }
        break;

      case Contents.Type.EMAIL:
        String emailData = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
        if (emailData != null) {
          contents = "mailto:" + emailData;
          displayContents = emailData;
          title = activity.getString(R.string.contents_email);
        }
        break;

      case Contents.Type.PHONE:
        String phoneData = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
        if (phoneData != null) {
          contents = "tel:" + phoneData;
          displayContents = PhoneNumberUtils.formatNumber(phoneData);
          title = activity.getString(R.string.contents_phone);
        }
        break;

      case Contents.Type.SMS:
        String smsData = ContactEncoder.trim(intent.getStringExtra(Intents.Encode.DATA));
        if (smsData != null) {
          contents = "sms:" + smsData;
          displayContents = PhoneNumberUtils.formatNumber(smsData);
          title = activity.getString(R.string.contents_sms);
        }
        break;

      case Contents.Type.CONTACT:
        Bundle contactBundle = intent.getBundleExtra(Intents.Encode.DATA);
        if (contactBundle != null) {

          String name = contactBundle.getString(ContactsContract.Intents.Insert.NAME);
          String organization = contactBundle.getString(ContactsContract.Intents.Insert.COMPANY);
          String address = contactBundle.getString(ContactsContract.Intents.Insert.POSTAL);
          List<String> phones = getAllBundleValues(contactBundle, Contents.PHONE_KEYS);
          List<String> phoneTypes = getAllBundleValues(contactBundle, Contents.PHONE_TYPE_KEYS);
          List<String> emails = getAllBundleValues(contactBundle, Contents.EMAIL_KEYS);
          String url = contactBundle.getString(Contents.URL_KEY);
          List<String> urls = url == null ? null : Collections.singletonList(url);
          String note = contactBundle.getString(Contents.NOTE_KEY);

          ContactEncoder encoder =
              useVCard ? new VCardContactEncoder() : new MECARDContactEncoder();
          String[] encoded =
              encoder.encode(
                  Collections.singletonList(name),
                  organization,
                  Collections.singletonList(address),
                  phones,
                  phoneTypes,
                  emails,
                  urls,
                  note);
          // Make sure we've encoded at least one field.
          if (!encoded[1].isEmpty()) {
            contents = encoded[0];
            displayContents = encoded[1];
            title = activity.getString(R.string.contents_contact);
          }
        }
        break;

      case Contents.Type.LOCATION:
        Bundle locationBundle = intent.getBundleExtra(Intents.Encode.DATA);
        if (locationBundle != null) {
          // These must use Bundle.getFloat(), not getDouble(), it's part of the API.
          float latitude = locationBundle.getFloat("LAT", Float.MAX_VALUE);
          float longitude = locationBundle.getFloat("LONG", Float.MAX_VALUE);
          if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
            contents = "geo:" + latitude + ',' + longitude;
            displayContents = latitude + "," + longitude;
            title = activity.getString(R.string.contents_location);
          }
        }
        break;
    }
  }
  private void encodeQRCodeContents(String data, Bundle bundle, String type) {
    if (type.equals(Contents.Type.TEXT)) {
      if (data != null && data.length() > 0) {
        contents = data;
        displayContents = data;
        title = "Text";
      }
    } else if (type.equals(Contents.Type.EMAIL)) {
      data = trim(data);
      if (data != null) {
        contents = "mailto:" + data;
        displayContents = data;
        title = "E-Mail";
      }
    } else if (type.equals(Contents.Type.PHONE)) {
      data = trim(data);
      if (data != null) {
        contents = "tel:" + data;
        displayContents = PhoneNumberUtils.formatNumber(data);
        title = "Phone";
      }
    } else if (type.equals(Contents.Type.SMS)) {
      data = trim(data);
      if (data != null) {
        contents = "sms:" + data;
        displayContents = PhoneNumberUtils.formatNumber(data);
        title = "SMS";
      }
    } else if (type.equals(Contents.Type.CONTACT)) {
      if (bundle != null) {
        StringBuilder newContents = new StringBuilder(100);
        StringBuilder newDisplayContents = new StringBuilder(100);

        newContents.append("MECARD:");

        String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
        if (name != null) {
          newContents.append("N:").append(escapeMECARD(name)).append(';');
          newDisplayContents.append(name);
        }

        String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
        if (address != null) {
          newContents.append("ADR:").append(escapeMECARD(address)).append(';');
          newDisplayContents.append('\n').append(address);
        }

        Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
        for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
          String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
          if (phone != null) {
            uniquePhones.add(phone);
          }
        }
        for (String phone : uniquePhones) {
          newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
          newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
        }

        Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
        for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
          String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
          if (email != null) {
            uniqueEmails.add(email);
          }
        }
        for (String email : uniqueEmails) {
          newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
          newDisplayContents.append('\n').append(email);
        }

        String url = trim(bundle.getString(Contents.URL_KEY));
        if (url != null) {
          // escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
          newContents.append("URL:").append(url).append(';');
          newDisplayContents.append('\n').append(url);
        }

        String note = trim(bundle.getString(Contents.NOTE_KEY));
        if (note != null) {
          newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
          newDisplayContents.append('\n').append(note);
        }

        // Make sure we've encoded at least one field.
        if (newDisplayContents.length() > 0) {
          newContents.append(';');
          contents = newContents.toString();
          displayContents = newDisplayContents.toString();
          title = "Contact";
        } else {
          contents = null;
          displayContents = null;
        }
      }
    } else if (type.equals(Contents.Type.LOCATION)) {
      if (bundle != null) {
        // These must use Bundle.getFloat(), not getDouble(), it's part of the API.
        float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
        float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
        if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
          contents = "geo:" + latitude + ',' + longitude;
          displayContents = latitude + "," + longitude;
          title = "Location";
        }
      }
    }
  }