Example usage for android.text SpannableStringBuilder append

List of usage examples for android.text SpannableStringBuilder append

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder append.

Prototype

public SpannableStringBuilder append(char text) 

Source Link

Usage

From source file:com.github.irshulx.Components.InputExtensions.java

public CustomEditText getNewEditTextInst(final String hint, CharSequence text) {
    final CustomEditText editText = new CustomEditText(
            new ContextThemeWrapper(this.editorCore.getContext(), R.style.WysiwygEditText));
    addEditableStyling(editText);/* w  w w .  j  a v a2  s.  c  o  m*/
    editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    if (hint != null) {
        editText.setHint(hint);
    }
    if (text != null) {
        setText(editText, text);
    }

    /**
     * create tag for the editor
     */

    EditorControl editorTag = editorCore.createTag(EditorType.INPUT);
    editorTag.textSettings = new TextSettings(this.DEFAULT_TEXT_COLOR);
    editText.setTag(editorTag);
    editText.setBackgroundDrawable(
            ContextCompat.getDrawable(this.editorCore.getContext(), R.drawable.invisible_edit_text));
    editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            return editorCore.onKey(v, keyCode, event, editText);
        }
    });
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                editText.clearFocus();
            } else {
                editorCore.setActiveView(v);
            }
        }
    });
    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {

            String text = Html.toHtml(editText.getText());
            Object tag = editText.getTag(R.id.control_tag);
            if (s.length() == 0 && tag != null)
                editText.setHint(tag.toString());
            if (s.length() > 0) {
                /*
                 * if user had pressed enter, replace it with br
                 */
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == '\n') {
                        CharSequence subChars = s.subSequence(0, i);
                        SpannableStringBuilder ssb = new SpannableStringBuilder(subChars);
                        text = Html.toHtml(ssb);
                        if (text.length() > 0)
                            setText(editText, text);

                        if (i + 1 == s.length()) {
                            s.clear();
                        }

                        int index = editorCore.getParentView().indexOfChild(editText);
                        /* if the index was 0, set the placeholder to empty, behaviour happens when the user just press enter
                         */
                        if (index == 0) {
                            editText.setHint(null);
                            editText.setTag(R.id.control_tag, hint);
                        }
                        int position = index + 1;
                        CharSequence newText = null;
                        SpannableStringBuilder editable = new SpannableStringBuilder();
                        int lastIndex = s.length();
                        int nextIndex = i + 1;
                        if (nextIndex < lastIndex) {
                            newText = s.subSequence(nextIndex, lastIndex);
                            for (int j = 0; j < newText.length(); j++) {
                                editable.append(newText.charAt(j));
                                if (newText.charAt(j) == '\n') {
                                    editable.append('\n');
                                }
                            }
                        }
                        insertEditText(position, hint, editable);
                        break;
                    }
                }
            }
            if (editorCore.getEditorListener() != null) {
                editorCore.getEditorListener().onTextChanged(editText, s);
            }
        }
    });
    if (this.lineSpacing != -1) {
        setLineSpacing(editText, this.lineSpacing);
    }
    return editText;
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static CharSequence generateSearchName(String name, String name2, String q) {
    if (name == null && name2 == null) {
        return "";
    }//from  ww w  . j  a  va  2  s .  c om
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String wholeString = name;
    if (wholeString == null || wholeString.length() == 0) {
        wholeString = name2;
    } else if (name2 != null && name2.length() != 0) {
        wholeString += " " + name2;
    }
    wholeString = wholeString.trim();
    String lower = " " + wholeString.toLowerCase();

    int index;
    int lastIndex = 0;
    while ((index = lower.indexOf(" " + q, lastIndex)) != -1) {
        int idx = index - (index == 0 ? 0 : 1);
        int end = q.length() + (index == 0 ? 0 : 1) + idx;

        if (lastIndex != 0 && lastIndex != idx + 1) {
            builder.append(wholeString.substring(lastIndex, idx));
        } else if (lastIndex == 0 && idx != 0) {
            builder.append(wholeString.substring(0, idx));
        }

        String query = wholeString.substring(idx, Math.min(wholeString.length(), end));
        if (query.startsWith(" ")) {
            builder.append(" ");
        }
        query = query.trim();

        int start = builder.length();
        builder.append(query);
        builder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteBlueText4)),
                start, start + query.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        lastIndex = end;
    }

    if (lastIndex != -1 && lastIndex != wholeString.length()) {
        builder.append(wholeString.substring(lastIndex, wholeString.length()));
    }

    return builder;
}

From source file:com.juick.android.JuickMessagesAdapter.java

public static ParsedMessage formatMessageText(final Context ctx, final JuickMessage jmsg, boolean condensed) {
    if (jmsg.parsedText != null) {
        return (ParsedMessage) jmsg.parsedText; // was parsed before
    }//from  w  w  w. ja  v  a  2  s.  c  o m
    getColorTheme(ctx);
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    int spanOffset = 0;
    final boolean isMainMessage = jmsg.getRID() == 0;
    final boolean doCompactComment = !isMainMessage && compactComments;
    if (jmsg.continuationInformation != null) {
        ssb.append(jmsg.continuationInformation + "\n");
        ssb.setSpan(new StyleSpan(Typeface.ITALIC), spanOffset, ssb.length() - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    //
    // NAME
    //
    spanOffset = ssb.length();
    String name = '@' + jmsg.User.UName;
    int userNameStart = ssb.length();
    ssb.append(name);
    int userNameEnd = ssb.length();
    StyleSpan userNameBoldSpan;
    ForegroundColorSpan userNameColorSpan;
    ssb.setSpan(userNameBoldSpan = new StyleSpan(Typeface.BOLD), spanOffset, ssb.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.setSpan(
            userNameColorSpan = new ForegroundColorSpan(
                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME, 0xFFC8934E)),
            spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    ssb.append(' ');
    spanOffset = ssb.length();

    if (!condensed) {
        //
        // TAGS
        //
        String tags = jmsg.getTags();
        if (feedlyFonts)
            tags = tags.toUpperCase();
        ssb.append(tags + "\n");
        if (tags.length() > 0) {
            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TAGS, 0xFF0000CC)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (feedlyFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.dinWebPro), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (helvNueFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        spanOffset = ssb.length();
    }
    if (jmsg.translated) {
        //
        // 'translated'
        //
        ssb.append("translated: ");
        ssb.setSpan(
                new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    int bodyOffset = ssb.length();
    int messageNumberStart = -1, messageNumberEnd = -1;
    if (showNumbers(ctx) && !condensed) {
        //
        // numbers
        //
        if (isMainMessage) {
            messageNumberStart = ssb.length();
            ssb.append(jmsg.getDisplayMessageNo());
            messageNumberEnd = ssb.length();
        } else {
            ssb.append("/" + jmsg.getRID());
            if (jmsg.getReplyTo() != 0) {
                ssb.append("->" + jmsg.getReplyTo());
            }
        }
        ssb.append(" ");
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.MESSAGE_ID, 0xFFa0a5bd)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    //
    // MESSAGE BODY
    //
    String txt = Censor.getCensoredText(jmsg.Text);
    if (!condensed) {
        if (jmsg.Photo != null) {
            txt = jmsg.Photo + "\n" + txt;
        }
        if (jmsg.Video != null) {
            txt = jmsg.Video + "\n" + txt;
        }
    }
    ssb.append(txt);
    boolean ssbChanged = false; // allocation optimization
    // Highlight links http://example.com/
    ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(txt, jmsg.getMID());
    ArrayList<String> urls = new ArrayList<String>();
    for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) {
        setSSBSpan(ssb, new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + foundURL.start, spanOffset + foundURL.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        urls.add(foundURL.url);
        if (foundURL.title != null) {
            ssb.replace(spanOffset + foundURL.title.start - 1, spanOffset + foundURL.title.start, " ");
            ssb.replace(spanOffset + foundURL.title.end, spanOffset + foundURL.title.end + 1, " ");
            ssb.replace(spanOffset + foundURL.start - 1, spanOffset + foundURL.start, "(");
            ssb.replace(spanOffset + foundURL.end, spanOffset + foundURL.end + 1, ")");
            ssb.setSpan(new StyleSpan(Typeface.BOLD), spanOffset + foundURL.title.start,
                    spanOffset + foundURL.title.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        ssbChanged = true;
    }
    // bold italic underline
    if (jmsg.Text.indexOf("*") != -1) {
        setStyleSpans(ssb, spanOffset, Typeface.BOLD, "*");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("/") != 0) {
        setStyleSpans(ssb, spanOffset, Typeface.ITALIC, "/");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("_") != 0) {
        setStyleSpans(ssb, spanOffset, UnderlineSpan.class, "_");
        ssbChanged = true;
    }
    if (ssbChanged) {
        txt = ssb.subSequence(spanOffset, ssb.length()).toString(); // ssb was modified in between
    }

    // Highlight nick
    String accountName = XMPPService.getMyAccountName(jmsg.getMID(), ctx);
    if (accountName != null) {
        int scan = spanOffset;
        String nickScanArea = (ssb + " ").toUpperCase();
        while (true) {
            int myNick = nickScanArea.indexOf("@" + accountName.toUpperCase(), scan);
            if (myNick != -1) {
                if (!isNickPart(nickScanArea.charAt(myNick + accountName.length() + 1))) {
                    setSSBSpan(ssb,
                            new BackgroundColorSpan(
                                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME_ME, 0xFF938e00)),
                            myNick - 1, myNick + accountName.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                scan = myNick + 1;
            } else {
                break;
            }
        }
    }

    // Highlight messages #1234
    int pos = 0;
    Matcher m = getCrossReferenceMsgPattern(jmsg.getMID()).matcher(txt);
    while (m.find(pos)) {
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + m.start(), spanOffset + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        pos = m.end();
    }

    SpannableStringBuilder compactDt = null;
    if (!condensed) {

        // found messages count (search results)
        if (jmsg.myFoundCount != 0 || jmsg.hisFoundCount != 0) {
            ssb.append("\n");
            int where = ssb.length();
            if (jmsg.myFoundCount != 0) {
                ssb.append(ctx.getString(R.string.MyReplies_) + jmsg.myFoundCount + "  ");
            }
            if (jmsg.hisFoundCount != 0) {
                ssb.append(ctx.getString(R.string.UserReplies_) + jmsg.hisFoundCount);
            }
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                    where, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        int rightPartOffset = spanOffset = ssb.length();

        if (!doCompactComment) {
            //
            // TIME (bottom of message)
            //

            try {
                DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                if (date.endsWith("/76"))
                    date = date.substring(0, date.length() - 3); // special case for no year in datasource
                ssb.append("\n" + date + " ");
            } catch (Exception e) {
                ssb.append("\n[fmt err] ");
            }

            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            compactDt = new SpannableStringBuilder();
            try {
                if (true || jmsg.deltaTime != Long.MIN_VALUE) {
                    compactDt.append(com.juickadvanced.Utils.toRelaviteDate(jmsg.Timestamp.getTime(), russian));
                } else {
                    DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                    String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                    if (date.endsWith("/76"))
                        date = date.substring(0, date.length() - 3); // special case for no year in datasource
                    compactDt.append(date);
                }
            } catch (Exception e) {
                compactDt.append("\n[fmt err] ");
            }
            compactDt.setSpan(
                    new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), 0,
                    compactDt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        spanOffset = ssb.length();

        //
        // Number of REPLIES
        //
        if (jmsg.replies > 0) {
            String replies = Replies + jmsg.replies;
            ssb.append(" " + replies);
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.NUMBER_OF_COMMENTS, 0xFFC8934E)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new WrapTogetherSpan() {
            }, spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!doCompactComment) {
            // right align
            ssb.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), rightPartOffset, ssb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), bodyOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    LeadingMarginSpan.LeadingMarginSpan2 userpicSpan = null;
    if (showUserpics(ctx) && !condensed) {
        userpicSpan = new LeadingMarginSpan.LeadingMarginSpan2() {
            @Override
            public int getLeadingMarginLineCount() {
                if (_wrapUserpics) {
                    return 2;
                } else {
                    return 22222;
                }
            }

            @Override
            public int getLeadingMargin(boolean first) {
                if (first) {
                    return (int) (2 * getLineHeight(ctx, (double) textScale));
                } else {
                    return 0;
                }
            }

            @Override
            public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                    CharSequence text, int start, int end, boolean first, Layout layout) {
            }
        };
        ssb.setSpan(userpicSpan, 0, ssb.length(), 0);
    }
    ParsedMessage parsedMessage = new ParsedMessage(ssb, urls);
    parsedMessage.userpicSpan = userpicSpan;
    parsedMessage.userNameBoldSpan = userNameBoldSpan;
    parsedMessage.userNameColorSpan = userNameColorSpan;
    parsedMessage.userNameStart = userNameStart;
    parsedMessage.userNameEnd = userNameEnd;
    parsedMessage.messageNumberStart = messageNumberStart;
    parsedMessage.messageNumberEnd = messageNumberEnd;
    parsedMessage.compactDate = compactDt;
    return parsedMessage;
}

From source file:com.android.mms.transaction.MessagingNotification.java

/**
 * updateNotification is *the* main function for building the actual notification handed to
 * the NotificationManager//from w ww  .ja  v a 2 s . co  m
 * @param context
 * @param newThreadId the new thread id
 * @param uniqueThreadCount
 * @param notificationSet the set of notifications to display
 */
private static void updateNotification(Context context, long newThreadId, int uniqueThreadCount,
        SortedSet<NotificationInfo> notificationSet) {
    boolean isNew = newThreadId != THREAD_NONE;
    CMConversationSettings conversationSettings = CMConversationSettings.getOrNew(context, newThreadId);

    // If the user has turned off notifications in settings, don't do any notifying.
    if ((isNew && !conversationSettings.getNotificationEnabled())
            || !MessagingPreferenceActivity.getNotificationEnabled(context)) {
        if (DEBUG) {
            Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
        }
        return;
    }

    // Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
    final int messageCount = notificationSet.size();
    NotificationInfo mostRecentNotification = notificationSet.first();

    final NotificationCompat.Builder noti = new NotificationCompat.Builder(context)
            .setWhen(mostRecentNotification.mTimeMillis);

    if (isNew) {
        noti.setTicker(mostRecentNotification.mTicker);
    }

    // If we have more than one unique thread, change the title (which would
    // normally be the contact who sent the message) to a generic one that
    // makes sense for multiple senders, and change the Intent to take the
    // user to the conversation list instead of the specific thread.

    // Cases:
    //   1) single message from single thread - intent goes to ComposeMessageActivity
    //   2) multiple messages from single thread - intent goes to ComposeMessageActivity
    //   3) messages from multiple threads - intent goes to ConversationList

    final Resources res = context.getResources();
    String title = null;
    Bitmap avatar = null;
    PendingIntent pendingIntent = null;
    boolean isMultiNewMessages = MessageUtils.isMailboxMode() ? messageCount > 1 : uniqueThreadCount > 1;
    if (isMultiNewMessages) { // messages from multiple threads
        Intent mainActivityIntent = getMultiThreadsViewIntent(context);
        pendingIntent = PendingIntent.getActivity(context, 0, mainActivityIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        title = context.getString(R.string.message_count_notification, messageCount);
    } else { // same thread, single or multiple messages
        title = mostRecentNotification.mTitle;
        avatar = mostRecentNotification.mSender.getAvatar(context);
        noti.setSubText(mostRecentNotification.mSimName); // no-op in single SIM case
        if (avatar != null) {
            // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
            // have to scale 'em up to 128x128 to fill the whole notification large icon.
            final int idealIconHeight = res
                    .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
            final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
            noti.setLargeIcon(BitmapUtil.getRoundedBitmap(avatar, idealIconWidth, idealIconHeight));
        }

        pendingIntent = PendingIntent.getActivity(context, 0, mostRecentNotification.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    // Always have to set the small icon or the notification is ignored
    noti.setSmallIcon(R.drawable.stat_notify_sms);

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);

    // Update the notification.
    noti.setContentTitle(title).setContentIntent(pendingIntent)
            .setColor(context.getResources().getColor(R.color.mms_theme_color))
            .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
                                                                                                                                                                                                                                  // from a favorite.

    // Tag notification with all senders.
    for (NotificationInfo info : notificationSet) {
        Uri peopleReferenceUri = info.mSender.getPeopleReferenceUri();
        if (peopleReferenceUri != null) {
            noti.addPerson(peopleReferenceUri.toString());
        }
    }

    int defaults = 0;

    if (isNew) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        if (conversationSettings.getVibrateEnabled()) {
            String pattern = conversationSettings.getVibratePattern();

            if (!TextUtils.isEmpty(pattern)) {
                noti.setVibrate(parseVibratePattern(pattern));
            } else {
                defaults |= Notification.DEFAULT_VIBRATE;
            }
        }

        String ringtoneStr = conversationSettings.getNotificationTone();
        noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
        Log.d(TAG, "updateNotification: new message, adding sound to the notification");
    }

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    // See if QuickMessage pop-up support is enabled in preferences
    boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);

    // Set up the QuickMessage intent
    Intent qmIntent = null;
    if (mostRecentNotification.mIsSms) {
        // QuickMessage support is only for SMS
        qmIntent = new Intent();
        qmIntent.setClass(context, QuickMessagePopup.class);
        qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
        qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
    }

    // Start getting the notification ready
    final Notification notification;

    //Create a WearableExtender to add actions too
    WearableExtender wearableExtender = new WearableExtender();

    if (messageCount == 1 || uniqueThreadCount == 1) {
        // Add the Quick Reply action only if the pop-up won't be shown already
        if (!qmPopupEnabled && qmIntent != null) {

            // This is a QR, we should show the keyboard when the user taps to reply
            qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);

            // Create the pending intent and add it to the notification
            CharSequence qmText = context.getText(R.string.menu_reply);
            PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);

            //Wearable
            noti.extend(wearableExtender.addAction(
                    new NotificationCompat.Action.Builder(R.drawable.ic_reply, qmText, qmPendingIntent)
                            .build()));
        }

        // Add the 'Mark as read' action
        CharSequence markReadText = context.getText(R.string.qm_mark_read);
        Intent mrIntent = new Intent();
        mrIntent.setClass(context, QmMarkRead.class);
        mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
        PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_mark_read, markReadText, mrPendingIntent);

        // Add the Call action
        CharSequence callText = context.getText(R.string.menu_call);
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + mostRecentNotification.mSender.getNumber()));
        PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);

        //Wearable
        noti.extend(wearableExtender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_menu_call, callText, callPendingIntent)
                        .build()));

        //Set up remote input
        String replyLabel = context.getString(R.string.qm_wear_voice_reply);
        RemoteInput remoteInput = new RemoteInput.Builder(QuickMessageWear.EXTRA_VOICE_REPLY)
                .setLabel(replyLabel).build();
        //Set up pending intent for voice reply
        Intent voiceReplyIntent = new Intent(context, QuickMessageWear.class);
        voiceReplyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_CONATCT, mostRecentNotification.mSender.getName());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_SENDER, mostRecentNotification.mSender.getNumber());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_THEAD_ID, mostRecentNotification.mThreadId);
        PendingIntent voiceReplyPendingIntent = PendingIntent.getActivity(context, 0, voiceReplyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        //Wearable voice reply action
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply,
                context.getString(R.string.qm_wear_reply_by_voice), voiceReplyPendingIntent)
                        .addRemoteInput(remoteInput).build();
        noti.extend(wearableExtender.addAction(action));
    }

    if (messageCount == 1) {
        // We've got a single message

        // This sets the text for the collapsed form:
        noti.setContentText(mostRecentNotification.formatBigMessage(context));

        if (mostRecentNotification.mAttachmentBitmap != null) {
            // The message has a picture, show that

            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(noti)
                    .bigPicture(mostRecentNotification.mAttachmentBitmap)
                    .setSummaryText(mostRecentNotification.formatPictureMessage(context));

            notification = noti.setStyle(bigPictureStyle).build();
        } else {
            // Show a single notification -- big style with the text of the whole message
            NotificationCompat.BigTextStyle bigTextStyle1 = new NotificationCompat.BigTextStyle(noti)
                    .bigText(mostRecentNotification.formatBigMessage(context));

            notification = noti.setStyle(bigTextStyle1).build();
        }
        if (DEBUG) {
            Log.d(TAG, "updateNotification: single message notification");
        }
    } else {
        // We've got multiple messages
        if (!isMultiNewMessages) {
            // We've got multiple messages for the same thread.
            // Starting with the oldest new message, display the full text of each message.
            // Begin a line for each subsequent message.
            SpannableStringBuilder buf = new SpannableStringBuilder();
            NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]);
            int len = infos.length;
            for (int i = len - 1; i >= 0; i--) {
                NotificationInfo info = infos[i];

                buf.append(info.formatBigMessage(context));

                if (i != 0) {
                    buf.append('\n');
                }
            }

            noti.setContentText(context.getString(R.string.message_count_notification, messageCount));

            // Show a single notification -- big style with the text of all the messages
            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
            bigTextStyle.bigText(buf)
                    // Forcibly show the last line, with the app's smallIcon in it, if we
                    // kicked the smallIcon out with an avatar bitmap
                    .setSummaryText((avatar == null) ? null : " ");
            notification = noti.setStyle(bigTextStyle).build();
            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages for single thread");
            }
        } else {
            // Build a set of the most recent notification per threadId.
            HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
            ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>();
            Iterator<NotificationInfo> notifications = notificationSet.iterator();
            while (notifications.hasNext()) {
                NotificationInfo notificationInfo = notifications.next();
                if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
                    uniqueThreads.add(notificationInfo.mThreadId);
                    mostRecentNotifPerThread.add(notificationInfo);
                }
            }
            // When collapsed, show all the senders like this:
            //     Fred Flinstone, Barry Manilow, Pete...
            noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(noti);

            // We have to set the summary text to non-empty so the content text doesn't show
            // up when expanded.
            inboxStyle.setSummaryText(" ");

            // At this point we've got multiple messages in multiple threads. We only
            // want to show the most recent message per thread, which are in
            // mostRecentNotifPerThread.
            int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
            int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);

            for (int i = 0; i < maxMessages; i++) {
                NotificationInfo info = mostRecentNotifPerThread.get(i);
                inboxStyle.addLine(info.formatInboxMessage(context));
            }
            notification = inboxStyle.build();

            uniqueThreads.clear();
            mostRecentNotifPerThread.clear();

            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification");
            }
        }
    }

    notifyUserIfFullScreen(context, title);
    nm.notify(NOTIFICATION_ID, notification);

    // Trigger the QuickMessage pop-up activity if enabled
    // But don't show the QuickMessage if the user is in a call or the phone is ringing
    if (qmPopupEnabled && qmIntent != null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE && !ConversationList.mIsRunning
                && !ComposeMessageActivity.mIsRunning) {
            context.startActivity(qmIntent);
        }
    }
}

From source file:com.android.screenspeak.speechrules.NodeSpeechRuleProcessor.java

/**
 * If the supplied node has a label, replaces the builder text with a
 * version formatted with the label.//from  w  w  w.j  a  v a  2s. com
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void formatTextWithLabel(AccessibilityNodeInfoCompat node, SpannableStringBuilder builder) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        return;

    // TODO(KM): add getLabeledBy to support lib
    AccessibilityNodeInfo info = (AccessibilityNodeInfo) node.getInfo();
    if (info == null)
        return;
    AccessibilityNodeInfo labeledBy = info.getLabeledBy();
    if (labeledBy == null)
        return;
    AccessibilityNodeInfoCompat labelNode = new AccessibilityNodeInfoCompat(labeledBy);

    final SpannableStringBuilder labelDescription = new SpannableStringBuilder();
    Set<AccessibilityNodeInfoCompat> visitedNodes = new HashSet<>();
    appendDescriptionForTree(labelNode, labelDescription, null, null, visitedNodes);
    AccessibilityNodeInfoUtils.recycleNodes(visitedNodes);
    if (TextUtils.isEmpty(labelDescription)) {
        return;
    }

    final String labeled = mContext.getString(R.string.template_labeled_item, builder, labelDescription);
    Spannable spannableLabeledText = StringBuilderUtils.createSpannableFromTextWithTemplate(labeled, builder);

    // Replace the text of the builder.
    builder.clear();
    builder.append(spannableLabeledText);
}

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

private void showMentionsNotification(AccountPreferences pref, long position) {
    final long accountId = pref.getAccountId();
    final Context context = getContext();
    final Resources resources = context.getResources();
    final NotificationManager nm = getNotificationManager();
    final Expression selection;
    if (pref.isNotificationFollowingOnly()) {
        selection = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId),
                Expression.greaterThan(Statuses.STATUS_ID, position),
                Expression.equals(Statuses.IS_FOLLOWING, 1));
    } else {/*  w w w . j a  va 2 s .  c  o m*/
        selection = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId),
                Expression.greaterThan(Statuses.STATUS_ID, position));
    }
    final String filteredSelection = Utils.buildStatusFilterWhereClause(Mentions.TABLE_NAME, selection)
            .getSQL();
    final String[] userProjection = { Statuses.USER_ID, Statuses.USER_NAME, Statuses.USER_SCREEN_NAME };
    final String[] statusProjection = { Statuses.STATUS_ID, Statuses.USER_ID, Statuses.USER_NAME,
            Statuses.USER_SCREEN_NAME, Statuses.TEXT_UNESCAPED, Statuses.STATUS_TIMESTAMP };
    final Cursor statusCursor = mDatabaseWrapper.query(Mentions.TABLE_NAME, statusProjection, filteredSelection,
            null, null, null, Statuses.SORT_ORDER_TIMESTAMP_DESC);
    final Cursor userCursor = mDatabaseWrapper.query(Mentions.TABLE_NAME, userProjection, filteredSelection,
            null, Statuses.USER_ID, null, Statuses.SORT_ORDER_TIMESTAMP_DESC);
    try {
        final int usersCount = userCursor.getCount();
        final int statusesCount = statusCursor.getCount();
        if (statusesCount == 0 || usersCount == 0)
            return;
        final String accountName = Utils.getAccountName(context, accountId);
        final String accountScreenName = Utils.getAccountScreenName(context, accountId);
        final int idxStatusText = statusCursor.getColumnIndex(Statuses.TEXT_UNESCAPED),
                idxStatusId = statusCursor.getColumnIndex(Statuses.STATUS_ID),
                idxStatusTimestamp = statusCursor.getColumnIndex(Statuses.STATUS_TIMESTAMP),
                idxStatusUserName = statusCursor.getColumnIndex(Statuses.USER_NAME),
                idxStatusUserScreenName = statusCursor.getColumnIndex(Statuses.USER_SCREEN_NAME),
                idxUserName = userCursor.getColumnIndex(Statuses.USER_NAME),
                idxUserScreenName = userCursor.getColumnIndex(Statuses.USER_NAME),
                idxUserId = userCursor.getColumnIndex(Statuses.USER_NAME);

        final CharSequence notificationTitle = resources.getQuantityString(R.plurals.N_new_mentions,
                statusesCount, statusesCount);
        final String notificationContent;
        userCursor.moveToFirst();
        final String displayName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId),
                mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName));
        if (usersCount == 1) {
            notificationContent = context.getString(R.string.notification_mention, displayName);
        } else {
            notificationContent = context.getString(R.string.notification_mention_multiple, displayName,
                    usersCount - 1);
        }

        // Add rich notification and get latest tweet timestamp
        long when = -1, statusId = -1;
        final InboxStyle style = new InboxStyle();
        for (int i = 0, j = Math.min(statusesCount, 5); statusCursor.moveToPosition(i) && i < j; i++) {
            if (when == -1) {
                when = statusCursor.getLong(idxStatusTimestamp);
            }
            if (statusId == -1) {
                statusId = statusCursor.getLong(idxStatusId);
            }
            final SpannableStringBuilder sb = new SpannableStringBuilder();
            sb.append(UserColorNameUtils.getUserNickname(context, statusCursor.getLong(idxUserId),
                    mNameFirst ? statusCursor.getString(idxStatusUserName)
                            : statusCursor.getString(idxStatusUserScreenName)));
            sb.setSpan(new StyleSpan(Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            sb.append(' ');
            sb.append(statusCursor.getString(idxStatusText));
            style.addLine(sb);
        }
        if (mNameFirst) {
            style.setSummaryText(accountName);
        } else {
            style.setSummaryText("@" + accountScreenName);
        }

        // Setup notification
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_stat_mention);
        builder.setTicker(notificationTitle);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationContent);
        builder.setCategory(NotificationCompat.CATEGORY_SOCIAL);
        builder.setContentIntent(getContentIntent(context, AUTHORITY_MENTIONS, accountId));
        builder.setDeleteIntent(getDeleteIntent(context, AUTHORITY_MENTIONS, accountId, statusId));
        builder.setNumber(statusesCount);
        builder.setWhen(when);
        builder.setStyle(style);
        builder.setColor(pref.getNotificationLightColor());
        setNotificationPreferences(builder, pref, pref.getMentionsNotificationType());
        nm.notify("mentions_" + accountId, NOTIFICATION_ID_MENTIONS_TIMELINE, builder.build());
        Utils.sendPebbleNotification(context, notificationContent);
    } finally {
        statusCursor.close();
        userCursor.close();
    }
}

From source file:com.newcell.calltext.ui.messages.ConversationsAdapter.java

private CharSequence formatMessage(Cursor cursor) {
    SpannableStringBuilder buf = new SpannableStringBuilder();
    /*//from  ww  w . j a  va2 s .  c om
    String remoteContact = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM));
    Log.i(TAG, "remoteContact: '" + remoteContact + "'");
    if (remoteContact.equals("SELF")) {
    remoteContact = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_TO));
    //            buf.append("To: ");
    }
    */

    String remoteContactFull = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM_FULL));

    Log.i(TAG, "RemoteContactFull::" + remoteContactFull);
    /*
    String newRemoteContact = SipUri.getPhoneNumberFromApiSipString(remoteContactFull);
    if(newRemoteContact != "") {
       remoteContactFull = newRemoteContact;
       remoteContactFull = "\"" + remoteContactFull 
      + "\" <sip:" 
      + remoteContactFull 
      + "@" + SipManager.SERVER_DOMAIN + ">";
    Log.i(TAG, "New remoteContactFull::" + remoteContactFull);
    }
    */

    CallerInfo callerInfo = CallerInfo.getCallerInfoFromSipUri(mContext, remoteContactFull);
    //Log.i(TAG, "CallerInfo.number: '" + callerInfo.phoneNumber + "'");

    if (callerInfo != null && callerInfo.contactExists) {
        buf.append(callerInfo.name);
        /*
         * 6/19/2014 Removed the addition of the phone number to the title when the recipient is a contact
         */
        //buf.append(" / ");
        //buf.append(SipUri.getDisplayedSimpleContact(remoteContactFull));
    } else {
        buf.append(SipUri.getDisplayedSimpleContact(remoteContactFull));
    }

    int counter = cursor.getInt(cursor.getColumnIndex("counter"));
    if (counter > 1) {
        buf.append(" (" + counter + ") ");
    }

    int read = cursor.getInt(cursor.getColumnIndex(SipMessage.FIELD_READ));
    // Unread messages are shown in bold
    if (read == 0) {
        buf.setSpan(STYLE_BOLD, 0, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    return buf;
}

From source file:com.android.talkback.speechrules.NodeSpeechRuleProcessor.java

/**
 * If the supplied node has a label, replaces the builder text with a
 * version formatted with the label.//from www  .  jav  a 2s .co  m
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void formatTextWithLabel(AccessibilityNodeInfoCompat node, SpannableStringBuilder builder) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        return;

    // TODO: add getLabeledBy to support lib
    AccessibilityNodeInfo info = (AccessibilityNodeInfo) node.getInfo();
    if (info == null)
        return;
    AccessibilityNodeInfo labeledBy = info.getLabeledBy();
    if (labeledBy == null)
        return;
    AccessibilityNodeInfoCompat labelNode = new AccessibilityNodeInfoCompat(labeledBy);

    final SpannableStringBuilder labelDescription = new SpannableStringBuilder();
    Set<AccessibilityNodeInfoCompat> visitedNodes = new HashSet<>();
    appendDescriptionForTree(labelNode, labelDescription, null, null, visitedNodes);
    AccessibilityNodeInfoUtils.recycleNodes(visitedNodes);
    if (TextUtils.isEmpty(labelDescription)) {
        return;
    }

    final String labeled = mContext.getString(R.string.template_labeled_item, builder, labelDescription);
    Spannable spannableLabeledText = StringBuilderUtils.createSpannableFromTextWithTemplate(labeled, builder);

    // Replace the text of the builder.
    builder.clear();
    builder.append(spannableLabeledText);
}

From source file:org.getlantern.firetweet.provider.FiretweetDataProvider.java

private void showMessagesNotification(AccountPreferences pref, StringLongPair[] pairs,
        ContentValues[] valuesArray) {//ww w. ja v  a  2  s . c  o m
    final long accountId = pref.getAccountId();
    final long prevOldestId = mReadStateManager.getPosition(TAG_OLDEST_MESSAGES, String.valueOf(accountId));
    long oldestId = -1;
    for (final ContentValues contentValues : valuesArray) {
        final long messageId = contentValues.getAsLong(DirectMessages.MESSAGE_ID);
        oldestId = oldestId < 0 ? messageId : Math.min(oldestId, messageId);
        if (messageId <= prevOldestId)
            return;
    }
    mReadStateManager.setPosition(TAG_OLDEST_MESSAGES, String.valueOf(accountId), oldestId, false);
    final Context context = getContext();
    final Resources resources = context.getResources();
    final NotificationManager nm = getNotificationManager();
    final ArrayList<Expression> orExpressions = new ArrayList<>();
    final String prefix = accountId + "-";
    final int prefixLength = prefix.length();
    final Set<Long> senderIds = new CompactHashSet<>();
    for (StringLongPair pair : pairs) {
        final String key = pair.getKey();
        if (key.startsWith(prefix)) {
            final long senderId = Long.parseLong(key.substring(prefixLength));
            senderIds.add(senderId);
            final Expression expression = Expression.and(Expression.equals(DirectMessages.SENDER_ID, senderId),
                    Expression.greaterThan(DirectMessages.MESSAGE_ID, pair.getValue()));
            orExpressions.add(expression);
        }
    }
    orExpressions
            .add(Expression.notIn(new Column(DirectMessages.SENDER_ID), new RawItemArray(senderIds.toArray())));
    final Expression selection = Expression.and(Expression.equals(DirectMessages.ACCOUNT_ID, accountId),
            Expression.greaterThan(DirectMessages.MESSAGE_ID, prevOldestId),
            Expression.or(orExpressions.toArray(new Expression[orExpressions.size()])));
    final String filteredSelection = selection.getSQL();
    final String[] userProjection = { DirectMessages.SENDER_ID, DirectMessages.SENDER_NAME,
            DirectMessages.SENDER_SCREEN_NAME };
    final String[] messageProjection = { DirectMessages.MESSAGE_ID, DirectMessages.SENDER_ID,
            DirectMessages.SENDER_NAME, DirectMessages.SENDER_SCREEN_NAME, DirectMessages.TEXT_UNESCAPED,
            DirectMessages.MESSAGE_TIMESTAMP };
    final Cursor messageCursor = mDatabaseWrapper.query(DirectMessages.Inbox.TABLE_NAME, messageProjection,
            filteredSelection, null, null, null, DirectMessages.DEFAULT_SORT_ORDER);
    final Cursor userCursor = mDatabaseWrapper.query(DirectMessages.Inbox.TABLE_NAME, userProjection,
            filteredSelection, null, DirectMessages.SENDER_ID, null, DirectMessages.DEFAULT_SORT_ORDER);
    try {
        final int usersCount = userCursor.getCount();
        final int messagesCount = messageCursor.getCount();
        if (messagesCount == 0 || usersCount == 0)
            return;
        final String accountName = Utils.getAccountName(context, accountId);
        final String accountScreenName = Utils.getAccountScreenName(context, accountId);
        final int idxMessageText = messageCursor.getColumnIndex(DirectMessages.TEXT_UNESCAPED),
                idxMessageTimestamp = messageCursor.getColumnIndex(DirectMessages.MESSAGE_TIMESTAMP),
                idxMessageId = messageCursor.getColumnIndex(DirectMessages.MESSAGE_ID),
                idxMessageUserId = messageCursor.getColumnIndex(DirectMessages.SENDER_ID),
                idxMessageUserName = messageCursor.getColumnIndex(DirectMessages.SENDER_NAME),
                idxMessageUserScreenName = messageCursor.getColumnIndex(DirectMessages.SENDER_SCREEN_NAME),
                idxUserName = userCursor.getColumnIndex(DirectMessages.SENDER_NAME),
                idxUserScreenName = userCursor.getColumnIndex(DirectMessages.SENDER_NAME),
                idxUserId = userCursor.getColumnIndex(DirectMessages.SENDER_NAME);

        final CharSequence notificationTitle = resources.getQuantityString(R.plurals.N_new_messages,
                messagesCount, messagesCount);
        final String notificationContent;
        userCursor.moveToFirst();
        final String displayName = UserColorNameUtils.getUserNickname(context, userCursor.getLong(idxUserId),
                mNameFirst ? userCursor.getString(idxUserName) : userCursor.getString(idxUserScreenName));
        if (usersCount == 1) {
            if (messagesCount == 1) {
                notificationContent = context.getString(R.string.notification_direct_message, displayName);
            } else {
                notificationContent = context.getString(R.string.notification_direct_message_multiple_messages,
                        displayName, messagesCount);
            }
        } else {
            notificationContent = context.getString(R.string.notification_direct_message_multiple_users,
                    displayName, usersCount - 1, messagesCount);
        }

        final LongSparseArray<Long> idsMap = new LongSparseArray<>();
        // Add rich notification and get latest tweet timestamp
        long when = -1;
        final InboxStyle style = new InboxStyle();
        for (int i = 0; messageCursor.moveToPosition(i) && i < messagesCount; i++) {
            if (when < 0) {
                when = messageCursor.getLong(idxMessageTimestamp);
            }
            if (i < 5) {
                final SpannableStringBuilder sb = new SpannableStringBuilder();
                sb.append(UserColorNameUtils.getUserNickname(context, messageCursor.getLong(idxUserId),
                        mNameFirst ? messageCursor.getString(idxMessageUserName)
                                : messageCursor.getString(idxMessageUserScreenName)));
                sb.setSpan(new StyleSpan(Typeface.BOLD), 0, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                sb.append(' ');
                sb.append(messageCursor.getString(idxMessageText));
                style.addLine(sb);
            }
            final long userId = messageCursor.getLong(idxMessageUserId);
            final long messageId = messageCursor.getLong(idxMessageId);
            idsMap.put(userId, Math.max(idsMap.get(userId, -1L), messageId));
        }
        if (mNameFirst) {
            style.setSummaryText(accountName);
        } else {
            style.setSummaryText("@" + accountScreenName);
        }
        final StringLongPair[] positions = new StringLongPair[idsMap.size()];
        for (int i = 0, j = idsMap.size(); i < j; i++) {
            positions[i] = new StringLongPair(String.valueOf(idsMap.keyAt(i)), idsMap.valueAt(i));
        }

        // Setup notification
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setAutoCancel(true);
        builder.setSmallIcon(R.drawable.ic_stat_direct_message);
        builder.setTicker(notificationTitle);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationContent);
        builder.setCategory(NotificationCompat.CATEGORY_SOCIAL);
        builder.setContentIntent(getContentIntent(context, AUTHORITY_DIRECT_MESSAGES, accountId));
        builder.setContentIntent(getDeleteIntent(context, AUTHORITY_DIRECT_MESSAGES, accountId, positions));
        builder.setNumber(messagesCount);
        builder.setWhen(when);
        builder.setStyle(style);
        builder.setColor(pref.getNotificationLightColor());
        setNotificationPreferences(builder, pref, pref.getDirectMessagesNotificationType());
        nm.notify("messages_" + accountId, NOTIFICATION_ID_DIRECT_MESSAGES, builder.build());
        Utils.sendPebbleNotification(context, notificationContent);
    } finally {
        messageCursor.close();
        userCursor.close();
    }
}

From source file:com.hippo.ehviewer.ui.scene.GalleryListScene.java

private void setSearchBarHint(Context context, SearchBar searchBar) {
    Resources resources = context.getResources();
    Drawable searchImage = DrawableManager.getDrawable(context, R.drawable.v_magnify_x24);
    SpannableStringBuilder ssb = new SpannableStringBuilder("   ");
    ssb.append(resources.getString(
            EhUrl.SITE_EX == Settings.getGallerySite() ? R.string.gallery_list_search_bar_hint_exhentai
                    : R.string.gallery_list_search_bar_hint_e_hentai));
    int textSize = (int) (searchBar.getEditTextTextSize() * 1.25);
    if (searchImage != null) {
        searchImage.setBounds(0, 0, textSize, textSize);
        ssb.setSpan(new ImageSpan(searchImage), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }//from   w  w w .  ja v a 2s .c o m
    searchBar.setEditTextHint(ssb);
}