Example usage for android.content.res Resources getQuantityString

List of usage examples for android.content.res Resources getQuantityString

Introduction

In this page you can find the example usage for android.content.res Resources getQuantityString.

Prototype

@NonNull
public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs)
        throws NotFoundException 

Source Link

Document

Formats the string necessary for grammatically correct pluralization of the given resource ID for the given quantity, using the given arguments.

Usage

From source file:com.ichi2.anki2.DeckPicker.java

private void updateDecksList(TreeSet<Object[]> decks, int eta, int count) {
    if (decks == null) {
        Log.e(AnkiDroidApp.TAG, "updateDecksList: empty decks list");
        return;/*from  www .  j a  va 2  s  .  co  m*/
    }
    mDeckList.clear();
    int due = 0;
    for (Object[] d : decks) {
        HashMap<String, String> m = new HashMap<String, String>();
        String[] name = ((String[]) d[0]);
        m.put("name", readableDeckName(name));
        m.put("did", ((Long) d[1]).toString());
        m.put("new", ((Integer) d[2]).toString());
        m.put("lrn", ((Integer) d[3]).toString());
        m.put("rev", ((Integer) d[4]).toString());
        m.put("dyn", ((Boolean) d[5]) ? "d1" : "d0");
        // m.put("complMat", ((Float)d[5]).toString());
        // m.put("complAll", ((Float)d[6]).toString());
        if (name.length == 1) {
            due += Integer.parseInt(m.get("new")) + Integer.parseInt(m.get("lrn"))
                    + Integer.parseInt(m.get("rev"));
            // top position
            m.put("sep", "top");
            // correct previous deck
            if (mDeckList.size() > 0) {
                HashMap<String, String> map = mDeckList.get(mDeckList.size() - 1);
                if (map.get("sep").equals("top")) {
                    map.put("sep", "ful");
                } else {
                    map.put("sep", "bot");
                }
            }
        } else {
            // center position
            m.put("sep", "cen");
        }
        if (mDeckList.size() > 0 && mDeckList.size() == decks.size() - 1) {
            // bottom position
            if (name.length == 1) {
                m.put("sep", "ful");
            } else {
                m.put("sep", "bot");
            }
        }
        mDeckList.add(m);
    }
    mDeckListAdapter.notifyDataSetChanged();

    // set title
    Resources res = getResources();
    if (count != -1) {
        String time = "-";
        if (eta != -1) {
            time = res.getQuantityString(R.plurals.deckpicker_title_minutes, eta, eta);
        }
        AnkiDroidApp.getCompat().setSubtitle(this,
                res.getQuantityString(R.plurals.deckpicker_title, due, due, count, time));
    }
    setTitle(res.getString(R.string.app_name));

    // update widget
    WidgetStatus.update(this, decks);
}

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  v  a 2s.  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.novoda.downloadmanager.lib.DownloadNotifier.java

private Notification buildTitlesAndDescription(Resources res, int type, Collection<DownloadInfo> cluster,
        NotificationCompat.Builder builder) {
    String remainingText = null;//  ww  w  .j  a  v a  2 s.  c  o m
    String percentText = null;
    if (type == TYPE_ACTIVE) {
        long current = 0;
        long total = 0;
        long speed = 0;
        synchronized (mDownloadSpeed) {
            for (DownloadInfo info : cluster) {
                if (mDownloadSpeed.get(info.mId) == null) {
                    continue;
                }
                if (info.mTotalBytes != -1) {
                    current += info.mCurrentBytes;
                    total += info.mTotalBytes;
                    speed += mDownloadSpeed.get(info.mId);
                }
            }
        }

        if (total > 0) {
            final int percent = (int) ((current * 100) / total);
            percentText = percent + "%";//res.getString(R.string.download_percent, percent);

            if (speed > 0) {
                final long remainingMillis = ((total - current) * 1000) / speed;
                remainingText = "Duration " + formatDuration(remainingMillis);
            }

            builder.setProgress(100, percent, false);
        } else {
            builder.setProgress(100, 0, true);
        }
    }

    if (cluster.size() == 1) {
        final DownloadInfo info = cluster.iterator().next();

        final NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
        String imageUrl = info.bigPictureResourceUrl;
        if (!TextUtils.isEmpty(imageUrl)) {
            Bitmap bitmap = imageRetriever.retrieveImage(imageUrl);
            style.bigPicture(bitmap);
        }
        builder.setContentTitle(getDownloadTitle(res, info));
        style.setBigContentTitle(getDownloadTitle(res, info));

        if (type == TYPE_ACTIVE) {
            if (!TextUtils.isEmpty(info.mDescription)) {
                builder.setContentText(info.mDescription);
                style.setSummaryText(info.mDescription);
            } else {
                builder.setContentText(remainingText);
                style.setSummaryText(remainingText);
            }
            builder.setContentInfo(percentText);

        } else if (type == TYPE_WAITING) {
            builder.setContentText("Download size requires Wi-Fi.");
            style.setSummaryText("Download size requires Wi-Fi.");

        } else if (type == TYPE_COMPLETE) {
            if (Downloads.Impl.isStatusError(info.mStatus)) {
                builder.setContentText("Download unsuccessful.");
                style.setSummaryText("Download unsuccessful.");
            } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                builder.setContentText("Download complete.");
                style.setSummaryText("Download complete.");
            }
        }

        if (!TextUtils.isEmpty(imageUrl)) {
            builder.setStyle(style);
        }
        return builder.build();

    } else

    {
        final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);

        for (DownloadInfo info : cluster) {
            inboxStyle.addLine(getDownloadTitle(res, info));
        }

        if (type == TYPE_ACTIVE) {
            builder.setContentTitle(
                    res.getQuantityString(R.plurals.dl__notif_summary_active, cluster.size(), cluster.size()));
            builder.setContentText(remainingText);
            builder.setContentInfo(percentText);
            inboxStyle.setSummaryText(remainingText);

        } else if (type == TYPE_WAITING) {
            builder.setContentTitle(
                    res.getQuantityString(R.plurals.dl__notif_summary_waiting, cluster.size(), cluster.size()));
            builder.setContentText("Download size requires Wi-Fi.");
            inboxStyle.setSummaryText("Download size requires Wi-Fi.");
        }

        return inboxStyle.build();
    }

}

From source file:io.plaidapp.ui.DribbbleShot.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dribbble_shot);
    shot = getIntent().getParcelableExtra(EXTRA_SHOT);
    setupDribbble();/*from  w  ww .  ja  v  a2 s .com*/
    setExitSharedElementCallback(fabLoginSharedElementCallback);
    getWindow().getSharedElementReturnTransition().addListener(shotReturnHomeListener);
    circleTransform = new CircleTransform(this);
    Resources res = getResources();

    ButterKnife.bind(this);
    View shotDescription = getLayoutInflater().inflate(R.layout.dribbble_shot_description, commentsList, false);
    shotSpacer = shotDescription.findViewById(R.id.shot_spacer);
    title = shotDescription.findViewById(R.id.shot_title);
    description = shotDescription.findViewById(R.id.shot_description);
    shotActions = (LinearLayout) shotDescription.findViewById(R.id.shot_actions);
    likeCount = (Button) shotDescription.findViewById(R.id.shot_like_count);
    viewCount = (Button) shotDescription.findViewById(R.id.shot_view_count);
    share = (Button) shotDescription.findViewById(R.id.shot_share_action);
    playerName = (TextView) shotDescription.findViewById(R.id.player_name);
    playerAvatar = (ImageView) shotDescription.findViewById(R.id.player_avatar);
    shotTimeAgo = (TextView) shotDescription.findViewById(R.id.shot_time_ago);
    commentsList = (ListView) findViewById(R.id.dribbble_comments);
    commentsList.addHeaderView(shotDescription);
    setupCommenting();
    commentsList.setOnScrollListener(scrollListener);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            expandImageAndFinish();
        }
    });
    fab.setOnClickListener(fabClick);
    chromeFader = new ElasticDragDismissFrameLayout.SystemChromeFader(getWindow()) {
        @Override
        public void onDragDismissed() {
            expandImageAndFinish();
        }
    };

    // load the main image
    final int[] imageSize = shot.images.bestSize();
    Glide.with(this).load(shot.images.best()).listener(shotLoadListener)
            .diskCacheStrategy(DiskCacheStrategy.SOURCE).priority(Priority.IMMEDIATE)
            .override(imageSize[0], imageSize[1]).into(imageView);
    imageView.setOnClickListener(shotClick);
    shotSpacer.setOnClickListener(shotClick);

    postponeEnterTransition();
    imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            imageView.getViewTreeObserver().removeOnPreDrawListener(this);
            calculateFabPosition();
            enterAnimation(savedInstanceState != null);
            startPostponedEnterTransition();
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ((FabOverlapTextView) title).setText(shot.title);
    } else {
        ((TextView) title).setText(shot.title);
    }
    if (!TextUtils.isEmpty(shot.description)) {
        final Spanned descText = shot.getParsedDescription(
                ContextCompat.getColorStateList(this, R.color.dribbble_links),
                ContextCompat.getColor(this, R.color.dribbble_link_highlight));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ((FabOverlapTextView) description).setText(descText);
        } else {
            HtmlUtils.setTextWithNiceLinks((TextView) description, descText);
        }
    } else {
        description.setVisibility(View.GONE);
    }
    NumberFormat nf = NumberFormat.getInstance();
    likeCount.setText(
            res.getQuantityString(R.plurals.likes, (int) shot.likes_count, nf.format(shot.likes_count)));
    // TODO onClick show likes
    viewCount.setText(
            res.getQuantityString(R.plurals.views, (int) shot.views_count, nf.format(shot.views_count)));
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new ShareDribbbleImageTask(DribbbleShot.this, shot).execute();
        }
    });
    if (shot.user != null) {
        playerName.setText("" + shot.user.name);
        Glide.with(this).load(shot.user.avatar_url).transform(circleTransform)
                .placeholder(R.drawable.avatar_placeholder).into(playerAvatar);
        playerAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DribbbleShot.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(shot.user.html_url)));
            }
        });
        if (shot.created_at != null) {
            shotTimeAgo.setText(DateUtils.getRelativeTimeSpanString(shot.created_at.getTime(),
                    System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS));
        }
    } else {
        playerName.setVisibility(View.GONE);
        playerAvatar.setVisibility(View.GONE);
        shotTimeAgo.setVisibility(View.GONE);
    }

    if (shot.comments_count > 0) {
        loadComments();
    } else {
        commentsList.setAdapter(getNoCommentsAdapter());
    }
}

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

private void showMessagesNotification(AccountPreferences pref, StringLongPair[] pairs,
        ContentValues[] valuesArray) {//from  w w w .j a  va 2s  .co  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.jio.appstore.download.DownloadNotifier.java

private void updateWithLocked(Collection<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();

    // Cluster downloads together
    final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
    for (DownloadInfo info : downloads) {
        final String tag = buildNotificationTag(info);
        if (tag != null) {
            clustered.put(tag, info);/*from  ww  w . ja  va 2 s.c o m*/
        }
    }

    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);

        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }

        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);

        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);

            final String action;
            if (Downloads.Impl.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                action = Constants.ACTION_OPEN;
            }

            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));

            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }

        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        Long spd = mDownloadSpeed.get(info.mId);
                        if (spd != null) {
                            speed += spd;
                        }
                        //                            speed += mDownloadSpeed.get(info.mId);
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);

                if (speed > 0) {
                    final long remainingMillis = ((total - current) * 1000) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            DateUtils.formatElapsedTime(remainingMillis));
                }

                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }

        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();

            builder.setContentTitle(getDownloadTitle(res, info));

            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);

            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_download_waiting));

            } else if (type == TYPE_COMPLETE) {
                if (Downloads.Impl.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }

            notif = builder.build();

        } else {
            final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);

            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }

            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);

            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_download_waiting));
                inboxStyle.setSummaryText(res.getString(R.string.notification_download_waiting));
            }

            notif = inboxStyle.build();
        }

        mNotifManager.notify(tag, 0, notif);
    }

    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}

From source file:com.android.providers.downloads.DownloadNotifier.java

private void updateWithLocked(Collection<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();

    // Cluster downloads together
    final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
    for (DownloadInfo info : downloads) {
        final String tag = buildNotificationTag(info);
        if (tag != null) {
            clustered.put(tag, info);//w  ww. ja  v  a 2 s  . c o m
        }
    }

    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);

        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }

        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);

        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);

            final String action;
            if (Downloads.Impl.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
                    action = Constants.ACTION_OPEN;
                } else {
                    action = Constants.ACTION_LIST;
                }
            }

            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));

            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }

        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        speed += mDownloadSpeed.get(info.mId);
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);

                if (speed > 0) {
                    final long remainingMillis = ((total - current) * 1000) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            //                                DateUtils.formatDuration(remainingMillis)); // FIXME 
                            "" + remainingMillis);
                }

                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }

        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();

            builder.setContentTitle(getDownloadTitle(res, info));

            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);

            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));

            } else if (type == TYPE_COMPLETE) {
                if (Downloads.Impl.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }

            notif = builder.build();

        } else {
            final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);

            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }

            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);

            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
                inboxStyle.setSummaryText(res.getString(R.string.notification_need_wifi_for_size));
            }

            notif = inboxStyle.build();
        }

        mNotifManager.notify(tag, 0, notif);
    }

    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}

From source file:com.snda.mymarket.providers.downloads.DownloadNotifier.java

private void updateWithLocked(LongSparseArray<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();
    // Cluster downloads together
    final Map<String, Collection<DownloadInfo>> clustered = new HashMap<String, Collection<DownloadInfo>>();
    for (int index = 0; index < downloads.size(); index++) {
        final String tag = buildNotificationTag(downloads.valueAt(index));
        if (tag != null) {
            Collection<DownloadInfo> arrDownloads = clustered.get(tag);
            if (arrDownloads == null) {
                arrDownloads = new ArrayList<DownloadInfo>();
                clustered.put(tag, arrDownloads);
            }//from   www .  j a  v a2s  . c  om
            arrDownloads.add(downloads.valueAt(index));
        }
    }
    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);
        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }
        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);
        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);
            final String action;
            if (Downloads.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                if (info.mDestination != Downloads.DESTINATION_SYSTEMCACHE_PARTITION) {
                    action = Constants.ACTION_OPEN;
                } else {
                    action = Constants.ACTION_LIST;
                }
            }
            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }
        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        speed += mDownloadSpeed.get(info.mId) == null ? 0 : mDownloadSpeed.get(info.mId);
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);
                if (speed > 0) {
                    final long remainingMillis = (total - current) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            DateUtils.formatDuration(remainingMillis));
                }
                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }
        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();
            builder.setContentTitle(getDownloadTitle(res, info));
            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);
            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
            } else if (type == TYPE_COMPLETE) {
                if (Downloads.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }
            notif = builder.build();
        } else {
            final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }
            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);
            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
                inboxStyle.setSummaryText(res.getString(R.string.notification_need_wifi_for_size));
            }
            notif = inboxStyle.build();
        }
        mNotifManager.notify(tag, 0, notif);
    }
    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}

From source file:cm.android.download.providers.downloads.DownloadNotifier.java

private void updateWithLocked(Collection<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();

    // Cluster downloads together
    final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
    for (DownloadInfo info : downloads) {
        final String tag = buildNotificationTag(info);
        if (tag != null) {
            clustered.put(tag, info);/* w  ww  .j  av  a 2  s . c o m*/
        }
    }

    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);

        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }

        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);

        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);

            final String action;
            if (Downloads.Impl.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
                    action = Constants.ACTION_OPEN;
                } else {
                    action = Constants.ACTION_LIST;
                }
            }

            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));

            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }

        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        Long l = mDownloadSpeed.get(info.mId);
                        if (l == null) {
                            l = 0L;
                        }
                        speed += l;
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);

                if (speed > 0) {
                    final long remainingMillis = ((total - current) * 1000) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            // DateUtils.formatDuration(remainingMillis));
                            // // FIXME
                            "" + Helpers.formatDuration(mContext, remainingMillis));
                }

                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }

        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();

            builder.setContentTitle(getDownloadTitle(res, info));

            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);

            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));

            } else if (type == TYPE_COMPLETE) {
                if (Downloads.Impl.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }

            notif = builder.build();

        } else {
            final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);

            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }

            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);

            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
                inboxStyle.setSummaryText(res.getString(R.string.notification_need_wifi_for_size));
            }

            notif = inboxStyle.build();
        }

        mNotifManager.notify(tag, 0, notif);
    }

    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}

From source file:tree.love.providers.downloads.DownloadNotifier.java

private void updateWithLocked(Collection<DownloadInfo> downloads) {
    final Resources res = mContext.getResources();

    // Cluster downloads together
    // final Multimap<String, DownloadInfo> clustered =
    // ArrayListMultimap.create();
    // for (DownloadInfo info : downloads) {
    // final String tag = buildNotificationTag(info);
    // if (tag != null) {
    // clustered.put(tag, info);
    // }/* w w  w  .ja va 2 s .  co  m*/
    // }

    final HashMap<String, List<DownloadInfo>> clustered = new HashMap<String, List<DownloadInfo>>();

    for (DownloadInfo info : downloads) {
        final String tag = buildNotificationTag(info);
        if (tag != null) {
            List<DownloadInfo> collection = clustered.get(clustered);
            if (collection == null) {
                collection = new ArrayList<DownloadInfo>();
                clustered.put(tag, collection);
            }
            collection.add(info);
            // clustered.put(tag, collection);
        }
    }

    // Build notification for each cluster
    for (String tag : clustered.keySet()) {
        final int type = getNotificationTagType(tag);
        final Collection<DownloadInfo> cluster = clustered.get(tag);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);

        // Use time when cluster was first shown to avoid shuffling
        final long firstShown;
        if (mActiveNotifs.containsKey(tag)) {
            firstShown = mActiveNotifs.get(tag);
        } else {
            firstShown = System.currentTimeMillis();
            mActiveNotifs.put(tag, firstShown);
        }
        builder.setWhen(firstShown);

        // Show relevant icon
        if (type == TYPE_ACTIVE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download);
        } else if (type == TYPE_WAITING) {
            builder.setSmallIcon(android.R.drawable.stat_sys_warning);
        } else if (type == TYPE_COMPLETE) {
            builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
        }

        // Build action intents
        if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
            // build a synthetic uri for intent identification purposes
            final Uri uri = new Uri.Builder().scheme("active-dl").appendPath(tag).build();
            final Intent intent = new Intent(Constants.ACTION_LIST, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
            builder.setOngoing(true);

        } else if (type == TYPE_COMPLETE) {
            final DownloadInfo info = cluster.iterator().next();
            final Uri uri = ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, info.mId);
            builder.setAutoCancel(true);

            final String action;
            if (Downloads.Impl.isStatusError(info.mStatus)) {
                action = Constants.ACTION_LIST;
            } else {
                if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
                    action = Constants.ACTION_OPEN;
                } else {
                    action = Constants.ACTION_LIST;
                }
            }

            final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
            intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS, getDownloadIds(cluster));
            builder.setContentIntent(
                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));

            final Intent hideIntent = new Intent(Constants.ACTION_HIDE, uri, mContext, DownloadReceiver.class);
            builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
        }

        // Calculate and show progress
        String remainingText = null;
        String percentText = null;
        if (type == TYPE_ACTIVE) {
            long current = 0;
            long total = 0;
            long speed = 0;
            synchronized (mDownloadSpeed) {
                for (DownloadInfo info : cluster) {
                    if (info.mTotalBytes != -1) {
                        current += info.mCurrentBytes;
                        total += info.mTotalBytes;
                        speed += mDownloadSpeed.get(info.mId);
                    }
                }
            }

            if (total > 0) {
                final int percent = (int) ((current * 100) / total);
                percentText = res.getString(R.string.download_percent, percent);

                if (speed > 0) {
                    final long remainingMillis = ((total - current) * 1000) / speed;
                    remainingText = res.getString(R.string.download_remaining,
                            // TODO
                            "" + remainingMillis);
                    // DateUtils.formatDuration(remainingMillis));
                }

                builder.setProgress(100, percent, false);
            } else {
                builder.setProgress(100, 0, true);
            }
        }

        // Build titles and description
        final Notification notif;
        if (cluster.size() == 1) {
            final DownloadInfo info = cluster.iterator().next();

            builder.setContentTitle(getDownloadTitle(res, info));

            if (type == TYPE_ACTIVE) {
                if (!TextUtils.isEmpty(info.mDescription)) {
                    builder.setContentText(info.mDescription);
                } else {
                    builder.setContentText(remainingText);
                }
                builder.setContentInfo(percentText);

            } else if (type == TYPE_WAITING) {
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));

            } else if (type == TYPE_COMPLETE) {
                if (Downloads.Impl.isStatusError(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_failed));
                } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                    builder.setContentText(res.getText(R.string.notification_download_complete));
                }
            }

            notif = builder.build();

        } else {
            final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);

            for (DownloadInfo info : cluster) {
                inboxStyle.addLine(getDownloadTitle(res, info));
            }

            if (type == TYPE_ACTIVE) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                builder.setContentText(remainingText);
                builder.setContentInfo(percentText);
                inboxStyle.setSummaryText(remainingText);

            } else if (type == TYPE_WAITING) {
                builder.setContentTitle(
                        res.getQuantityString(R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                builder.setContentText(res.getString(R.string.notification_need_wifi_for_size));
                inboxStyle.setSummaryText(res.getString(R.string.notification_need_wifi_for_size));
            }

            notif = inboxStyle.build();
        }

        mNotifManager.notify(tag, 0, notif);
    }

    // Remove stale tags that weren't renewed
    final Iterator<String> it = mActiveNotifs.keySet().iterator();
    while (it.hasNext()) {
        final String tag = it.next();
        if (!clustered.containsKey(tag)) {
            mNotifManager.cancel(tag, 0);
            it.remove();
        }
    }
}