Search in sources :

Example 6 with InboxStyle

use of android.support.v4.app.NotificationCompat.InboxStyle in project OneSignal-Android-SDK by OneSignal.

the class GenerateNotification method createSummaryNotification.

// This summary notification will be visible instead of the normal one on pre-Android 7.0 devices.
static void createSummaryNotification(NotificationGenerationJob notifJob, OneSignalNotificationBuilder notifBuilder) {
    boolean updateSummary = notifJob.restoring;
    JSONObject gcmBundle = notifJob.jsonPayload;
    String group = gcmBundle.optString("grp", null);
    Random random = new Random();
    PendingIntent summaryDeleteIntent = getNewActionPendingIntent(random.nextInt(), getNewBaseDeleteIntent(0).putExtra("summary", group));
    Notification summaryNotification;
    Integer summaryNotificationId = null;
    String firstFullData = null;
    Collection<SpannableString> summaryList = null;
    OneSignalDbHelper dbHelper = OneSignalDbHelper.getInstance(currentContext);
    Cursor cursor = null;
    try {
        SQLiteDatabase readableDb = dbHelper.getReadableDbWithRetries();
        String[] retColumn = { NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID, NotificationTable.COLUMN_NAME_FULL_DATA, NotificationTable.COLUMN_NAME_IS_SUMMARY, NotificationTable.COLUMN_NAME_TITLE, NotificationTable.COLUMN_NAME_MESSAGE };
        String whereStr = // Where String
        NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED + " = 0";
        String[] whereArgs = { group };
        // Make sure to omit any old existing matching android ids in-case we are replacing it.
        if (!updateSummary && notifJob.getAndroidId() != -1)
            whereStr += " AND " + NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID + " <> " + notifJob.getAndroidId();
        cursor = readableDb.query(NotificationTable.TABLE_NAME, retColumn, whereStr, whereArgs, // group by
        null, // filter by row groups
        null, // sort order, new to old
        NotificationTable._ID + " DESC");
        if (cursor.moveToFirst()) {
            SpannableString spannableString;
            summaryList = new ArrayList<>();
            do {
                if (cursor.getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_IS_SUMMARY)) == 1)
                    summaryNotificationId = cursor.getInt(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID));
                else {
                    String title = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_TITLE));
                    if (title == null)
                        title = "";
                    else
                        title += " ";
                    // Html.fromHtml("<strong>" + line1Title + "</strong> " + gcmBundle.getString("alert"));
                    String msg = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_MESSAGE));
                    spannableString = new SpannableString(title + msg);
                    if (title.length() > 0)
                        spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, title.length(), 0);
                    summaryList.add(spannableString);
                    if (firstFullData == null)
                        firstFullData = cursor.getString(cursor.getColumnIndex(NotificationTable.COLUMN_NAME_FULL_DATA));
                }
            } while (cursor.moveToNext());
            if (updateSummary && firstFullData != null) {
                try {
                    gcmBundle = new JSONObject(firstFullData);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    } finally {
        if (cursor != null && !cursor.isClosed())
            cursor.close();
    }
    if (summaryNotificationId == null) {
        summaryNotificationId = random.nextInt();
        createSummaryIdDatabaseEntry(dbHelper, group, summaryNotificationId);
    }
    PendingIntent summaryContentIntent = getNewActionPendingIntent(random.nextInt(), createBaseSummaryIntent(summaryNotificationId, gcmBundle, group));
    // 2 or more notifications with a group received, group them together as a single notification.
    if (summaryList != null && ((updateSummary && summaryList.size() > 1) || (!updateSummary && summaryList.size() > 0))) {
        int notificationCount = summaryList.size() + (updateSummary ? 0 : 1);
        String summaryMessage = gcmBundle.optString("grp_msg", null);
        if (summaryMessage == null)
            summaryMessage = notificationCount + " new messages";
        else
            summaryMessage = summaryMessage.replace("$[notif_count]", "" + notificationCount);
        NotificationCompat.Builder summaryBuilder = getBaseOneSignalNotificationBuilder(notifJob).compatBuilder;
        if (updateSummary)
            removeNotifyOptions(summaryBuilder);
        // The summary is designed to fit all notifications.
        //   Default small and large icons are used instead of the payload options to enforce this.
        summaryBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent).setContentTitle(currentContext.getPackageManager().getApplicationLabel(currentContext.getApplicationInfo())).setContentText(summaryMessage).setNumber(notificationCount).setSmallIcon(getDefaultSmallIconId()).setLargeIcon(getDefaultLargeIcon()).setOnlyAlertOnce(updateSummary).setGroup(group).setGroupSummary(true);
        if (!updateSummary)
            summaryBuilder.setTicker(summaryMessage);
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        // Add the latest notification to the summary
        if (!updateSummary) {
            String line1Title = gcmBundle.optString("title", null);
            if (line1Title == null)
                line1Title = "";
            else
                line1Title += " ";
            String message = gcmBundle.optString("alert");
            SpannableString spannableString = new SpannableString(line1Title + message);
            if (line1Title.length() > 0)
                spannableString.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, line1Title.length(), 0);
            inboxStyle.addLine(spannableString);
        }
        for (SpannableString line : summaryList) inboxStyle.addLine(line);
        inboxStyle.setBigContentTitle(summaryMessage);
        summaryBuilder.setStyle(inboxStyle);
        summaryNotification = summaryBuilder.build();
    } else {
        // First notification with this group key, post like a normal notification.
        NotificationCompat.Builder summaryBuilder = notifBuilder.compatBuilder;
        // We are re-using the notifBuilder from the normal notification so if a developer as an
        //    extender setup all the settings will carry over.
        // Note: However their buttons will not carry over as we need to be setup with this new summaryNotificationId.
        summaryBuilder.mActions.clear();
        addNotificationActionButtons(gcmBundle, summaryBuilder, summaryNotificationId, group);
        summaryBuilder.setContentIntent(summaryContentIntent).setDeleteIntent(summaryDeleteIntent).setOnlyAlertOnce(updateSummary).setGroup(group).setGroupSummary(true);
        summaryNotification = summaryBuilder.build();
        addXiaomiSettings(notifBuilder, summaryNotification);
    }
    NotificationManagerCompat.from(currentContext).notify(summaryNotificationId, summaryNotification);
}
Also used : JSONException(org.json.JSONException) SpannableString(android.text.SpannableString) OSUtils.getResourceString(com.onesignal.OSUtils.getResourceString) Cursor(android.database.Cursor) Notification(android.app.Notification) BigInteger(java.math.BigInteger) SpannableString(android.text.SpannableString) JSONObject(org.json.JSONObject) Random(java.util.Random) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) StyleSpan(android.text.style.StyleSpan) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent)

Example 7 with InboxStyle

use of android.support.v4.app.NotificationCompat.InboxStyle in project Remindy by abicelis.

the class NotificationUtil method displayLocationBasedNotification.

public static void displayLocationBasedNotification(Context context, int notificationId, String contentTitle, String contentText, List<Task> triggeredTasks) {
    NotificationCompat.Builder mBuilder;
    mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon_remindy_notification_small).setColor(ContextCompat.getColor(context, R.color.primary)).setVibrate(new long[] { 50, 50, 200, 50 }).setLights(ContextCompat.getColor(context, R.color.primary), 3000, 3000).setSound(Settings.System.DEFAULT_NOTIFICATION_URI).setContentTitle(contentTitle).setContentText(contentText).setAutoCancel(true).setPriority(Notification.PRIORITY_HIGH);
    if (triggeredTasks.size() == 1) {
        //Intent for "DONE" button on BigView style
        Intent setTaskDoneIntent = new Intent(context, TaskActionsIntentService.class);
        setTaskDoneIntent.setAction(TaskActionsIntentService.ACTION_SET_TASK_DONE);
        setTaskDoneIntent.putExtra(TaskActionsIntentService.PARAM_TASK_ID, triggeredTasks.get(0).getId());
        PendingIntent setTaskDonePendingIntent = PendingIntent.getService(context, triggeredTasks.get(0).getId(), setTaskDoneIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        //Intent for clicking notification
        Intent openTaskIntent = new Intent(context, TaskDetailActivity.class);
        openTaskIntent.putExtra(TASK_ID_TO_DISPLAY, triggeredTasks.get(0).getId());
        //openTaskIntent.setAction(String.valueOf(task.getId()));
        //openTaskIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        //openTaskIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        // Adds the back stack
        stackBuilder.addParentStack(TaskDetailActivity.class);
        // Adds the Intent to the top of the stack
        stackBuilder.addNextIntent(openTaskIntent);
        // Gets a PendingIntent containing the entire back stack
        PendingIntent openTaskPendingIntent = stackBuilder.getPendingIntent(triggeredTasks.get(0).getId(), PendingIntent.FLAG_UPDATE_CURRENT);
        //Add pendingIntent to notification
        mBuilder.setContentIntent(openTaskPendingIntent);
        mBuilder.addAction(R.drawable.icon_notification_done, context.getResources().getString(R.string.notification_big_view_set_done), setTaskDonePendingIntent);
        //Set BigView
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText));
    } else {
        //Intent for clicking notification
        Intent openHomeIntent = new Intent(context, HomeActivity.class);
        PendingIntent openHomePendingItent = PendingIntent.getActivity(context, Integer.MAX_VALUE, openHomeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        //InboxStyle BigView (Multiline!)
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        inboxStyle.setBigContentTitle(contentTitle);
        for (Task task : triggeredTasks) inboxStyle.addLine("- " + task.getTitle());
        //Add pendingIntent to notification
        mBuilder.setContentIntent(openHomePendingItent);
        //Set BigView
        mBuilder.setStyle(inboxStyle);
    }
    // Get an instance of the NotificationManager service
    NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    // Builds the notification and issues it.
    mNotifyMgr.notify(triggeredTasks.get(0).getId(), mBuilder.build());
}
Also used : Task(ve.com.abicelis.remindy.model.Task) NotificationManager(android.app.NotificationManager) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) NotificationCompat(android.support.v4.app.NotificationCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent) TaskStackBuilder(android.support.v4.app.TaskStackBuilder)

Example 8 with InboxStyle

use of android.support.v4.app.NotificationCompat.InboxStyle in project iosched by google.

the class SessionAlarmService method notifySessionFeedback.

/**
     *  A starred session is about to end. Notify the user to provide session feedback.
     *  Constructs and triggers a system notification. Does nothing if the session has already
     *  concluded.
     */
private void notifySessionFeedback(boolean debug) {
    LOGD(TAG, "Considering firing notification for session feedback.");
    if (debug) {
        LOGW(TAG, "Note: this is a debug notification.");
    }
    // Don't fire notification if this feature is disabled in settings
    if (!SettingsUtils.shouldShowSessionFeedbackReminders(this)) {
        LOGD(TAG, "Skipping session feedback notification. Disabled in settings.");
        return;
    }
    Cursor c = null;
    try {
        c = getContentResolver().query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionsNeedingFeedbackQuery.PROJECTION, SessionsNeedingFeedbackQuery.WHERE_CLAUSE, null, null);
        if (c == null) {
            return;
        }
        FeedbackHelper feedbackHelper = new FeedbackHelper(this);
        List<String> needFeedbackIds = new ArrayList<String>();
        List<String> needFeedbackTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            String sessionId = c.getString(SessionsNeedingFeedbackQuery.SESSION_ID);
            String sessionTitle = c.getString(SessionsNeedingFeedbackQuery.SESSION_TITLE);
            // Avoid repeated notifications.
            if (feedbackHelper.isFeedbackNotificationFiredForSession(sessionId)) {
                LOGD(TAG, "Skipping repeated session feedback notification for session '" + sessionTitle + "'");
                continue;
            }
            needFeedbackIds.add(sessionId);
            needFeedbackTitles.add(sessionTitle);
        }
        if (needFeedbackIds.size() == 0) {
            // the user has already been notified of all sessions needing feedback
            return;
        }
        LOGD(TAG, "Going forward with session feedback notification for " + needFeedbackIds.size() + " session(s).");
        final Resources res = getResources();
        Intent dismissalIntent = new Intent(ACTION_NOTIFICATION_DISMISSAL);
        PendingIntent dismissalPendingIntent = PendingIntent.getService(this, (int) new Date().getTime(), dismissalIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        String provideFeedbackTicker = res.getString(R.string.session_feedback_notification_ticker);
        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
        //noinspection deprecation Ignore getColor deprecation until minSdk = 16
        notifBuilder.setColor(getResources().getColor(R.color.theme_primary));
        notifBuilder.setContentText(provideFeedbackTicker).setTicker(provideFeedbackTicker).setSmallIcon(R.drawable.ic_stat_notification).setPriority(Notification.PRIORITY_LOW).setLocalOnly(// make it local to the phone
        true).setDeleteIntent(dismissalPendingIntent).setAutoCancel(true);
        if (needFeedbackIds.size() == 1) {
            // Only 1 session needs feedback
            Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(needFeedbackIds.get(0));
            PendingIntent pi = TaskStackBuilder.create(this).addNextIntent(new Intent(this, MyScheduleActivity.class)).addNextIntent(new Intent(Intent.ACTION_VIEW, sessionUri, this, SessionFeedbackActivity.class)).getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);
            notifBuilder.setContentTitle(needFeedbackTitles.get(0)).setContentIntent(pi);
        } else {
            // Show information about several sessions that need feedback
            PendingIntent pi = TaskStackBuilder.create(this).addNextIntent(new Intent(this, MyScheduleActivity.class)).getPendingIntent(1, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            inboxStyle.setBigContentTitle(provideFeedbackTicker);
            for (String title : needFeedbackTitles) {
                inboxStyle.addLine(title);
            }
            notifBuilder.setContentTitle(getResources().getQuantityString(R.plurals.session_plurals, needFeedbackIds.size(), needFeedbackIds.size())).setStyle(inboxStyle).setContentIntent(pi);
        }
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LOGD(TAG, "Now showing session feedback notification!");
        nm.notify(FEEDBACK_NOTIFICATION_ID, notifBuilder.build());
        for (int i = 0; i < needFeedbackIds.size(); i++) {
            feedbackHelper.setFeedbackNotificationAsFiredForSession(needFeedbackIds.get(i));
        }
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}
Also used : NotificationManager(android.app.NotificationManager) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) ArrayList(java.util.ArrayList) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Cursor(android.database.Cursor) Uri(android.net.Uri) Date(java.util.Date) FeedbackHelper(com.google.samples.apps.iosched.feedback.FeedbackHelper) MyScheduleActivity(com.google.samples.apps.iosched.myschedule.MyScheduleActivity) NotificationCompat(android.support.v4.app.NotificationCompat) Resources(android.content.res.Resources) PendingIntent(android.app.PendingIntent)

Example 9 with InboxStyle

use of android.support.v4.app.NotificationCompat.InboxStyle in project actor-platform by actorapp.

the class AndroidNotifications method onNotification.

@Override
public void onNotification(Messenger messenger, List<Notification> topNotifications, int messagesCount, int conversationsCount) {
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setAutoCancel(true);
    builder.setSmallIcon(R.drawable.ic_app_notify);
    builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
    builder.setCategory(NotificationCompat.CATEGORY_MESSAGE);
    int defaults = NotificationCompat.DEFAULT_LIGHTS;
    if (messenger.isNotificationVibrationEnabled()) {
        defaults |= NotificationCompat.DEFAULT_VIBRATE;
    }
    //        if (silentUpdate) {
    //            defaults = 0;
    //        }
    builder.setDefaults(defaults);
    // Wearable
    //        builder.extend(new NotificationCompat.WearableExtender()
    //                .setBackground(((BitmapDrawable) AppContext.getContext().getResources().getDrawable(R.drawable.wear_bg)).getBitmap())
    //                .setHintHideIcon(true));
    final Notification topNotification = topNotifications.get(topNotifications.size() - 1);
    //        if (!silentUpdate) {
    //            builder.setTicker(getNotificationTextFull(topNotification, messenger));
    //        }
    android.app.Notification result;
    if (messagesCount == 1) {
        // Single message notification
        final String sender = getNotificationSender(topNotification);
        //            final CharSequence text = bypass.markdownToSpannable(messenger().getFormatter().formatNotificationText(topNotification), true).toString();
        final CharSequence text = messenger.getFormatter().formatNotificationText(topNotification);
        visiblePeer = topNotification.getPeer();
        Avatar avatar = null;
        int id = 0;
        String avatarTitle = "";
        switch(visiblePeer.getPeerType()) {
            case PRIVATE:
                avatar = messenger().getUsers().get(visiblePeer.getPeerId()).getAvatar().get();
                id = messenger().getUsers().get(visiblePeer.getPeerId()).getId();
                avatarTitle = messenger().getUsers().get(visiblePeer.getPeerId()).getName().get();
                break;
            case GROUP:
                avatar = messenger().getGroups().get(visiblePeer.getPeerId()).getAvatar().get();
                id = messenger().getGroups().get(visiblePeer.getPeerId()).getId();
                avatarTitle = messenger().getGroups().get(visiblePeer.getPeerId()).getName().get();
                break;
        }
        Drawable avatarDrawable = new AvatarPlaceholderDrawable(avatarTitle, id, 18, context);
        result = buildSingleMessageNotification(avatarDrawable, builder, sender, text, topNotification);
        final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, result);
        if (avatar != null && avatar.getSmallImage() != null && avatar.getSmallImage().getFileReference() != null) {
            messenger.bindFile(avatar.getSmallImage().getFileReference(), true, new FileVMCallback() {

                @Override
                public void onNotDownloaded() {
                }

                @Override
                public void onDownloading(float progress) {
                }

                @Override
                public void onDownloaded(FileSystemReference reference) {
                    RoundedBitmapDrawable d = getRoundedBitmapDrawable(reference);
                    android.app.Notification result = buildSingleMessageNotification(d, builder, sender, text, topNotification);
                    //NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    manager.notify(NOTIFICATION_ID, result);
                }
            });
        } else {
            manager.notify(NOTIFICATION_ID, result);
        }
    } else if (conversationsCount == 1) {
        // Single conversation notification
        String sender = getNotificationSender(topNotification);
        builder.setContentTitle(sender);
        builder.setContentText(messagesCount + context.getString(R.string.notifications_single_conversation_аfter_messages_count));
        visiblePeer = topNotification.getPeer();
        final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        for (Notification n : topNotifications) {
            if (topNotification.getPeer().getPeerType() == PeerType.GROUP) {
                inboxStyle.addLine(getNotificationTextFull(n, messenger));
            } else {
                inboxStyle.addLine(messenger.getFormatter().formatNotificationText(n));
            }
        }
        inboxStyle.setSummaryText(messagesCount + context.getString(R.string.notifications_single_conversation_аfter_messages_count));
        Avatar avatar = null;
        int id = 0;
        String avatarTitle = "";
        switch(visiblePeer.getPeerType()) {
            case PRIVATE:
                avatar = messenger().getUsers().get(visiblePeer.getPeerId()).getAvatar().get();
                id = messenger().getUsers().get(visiblePeer.getPeerId()).getId();
                avatarTitle = messenger().getUsers().get(visiblePeer.getPeerId()).getName().get();
                break;
            case GROUP:
                avatar = messenger().getGroups().get(visiblePeer.getPeerId()).getAvatar().get();
                id = messenger().getGroups().get(visiblePeer.getPeerId()).getId();
                avatarTitle = messenger().getGroups().get(visiblePeer.getPeerId()).getName().get();
                break;
        }
        Drawable avatarDrawable = new AvatarPlaceholderDrawable(avatarTitle, id, 18, context);
        result = buildSingleConversationNotification(builder, inboxStyle, avatarDrawable, topNotification);
        final NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, result);
        if (avatar != null && avatar.getSmallImage() != null && avatar.getSmallImage().getFileReference() != null) {
            messenger.bindFile(avatar.getSmallImage().getFileReference(), true, new FileVMCallback() {

                @Override
                public void onNotDownloaded() {
                }

                @Override
                public void onDownloading(float progress) {
                }

                @Override
                public void onDownloaded(FileSystemReference reference) {
                    RoundedBitmapDrawable d = getRoundedBitmapDrawable(reference);
                    android.app.Notification result = buildSingleConversationNotification(builder, inboxStyle, d, topNotification);
                    manager.notify(NOTIFICATION_ID, result);
                }
            });
        } else {
            manager.notify(NOTIFICATION_ID, result);
        }
    } else {
        // Multiple conversations notification
        builder.setContentTitle(ActorSDK.sharedActor().getAppName());
        builder.setContentText(messagesCount + context.getString(R.string.notification_multiple_canversations_after_msg_count) + conversationsCount + context.getString(R.string.notifications_multiple_canversations_after_coversations_count));
        visiblePeer = null;
        intent = new Intent(context, RootActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        builder.setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        for (Notification n : topNotifications) {
            inboxStyle.addLine(getNotificationTextFull(n, messenger));
        }
        inboxStyle.setSummaryText(messagesCount + context.getString(R.string.notification_multiple_canversations_after_msg_count) + conversationsCount + context.getString(R.string.notifications_multiple_canversations_after_coversations_count));
        result = builder.setStyle(inboxStyle).build();
        addCustomLedAndSound(topNotification, result);
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, result);
    }
}
Also used : RoundedBitmapDrawable(android.support.v4.graphics.drawable.RoundedBitmapDrawable) FileSystemReference(im.actor.runtime.files.FileSystemReference) NotificationManager(android.app.NotificationManager) SpannableStringBuilder(android.text.SpannableStringBuilder) AvatarPlaceholderDrawable(im.actor.sdk.view.avatar.AvatarPlaceholderDrawable) Drawable(android.graphics.drawable.Drawable) RoundedBitmapDrawable(android.support.v4.graphics.drawable.RoundedBitmapDrawable) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Notification(im.actor.core.entity.Notification) Avatar(im.actor.core.entity.Avatar) NotificationCompat(android.support.v4.app.NotificationCompat) AvatarPlaceholderDrawable(im.actor.sdk.view.avatar.AvatarPlaceholderDrawable) FileVMCallback(im.actor.core.viewmodel.FileVMCallback)

Example 10 with InboxStyle

use of android.support.v4.app.NotificationCompat.InboxStyle in project SeriesGuide by UweTrottmann.

the class NotificationService method onNotify.

private void onNotify(final Cursor upcomingEpisodes, List<Integer> notifyPositions, long latestAirtime) {
    final Context context = getApplicationContext();
    CharSequence tickerText;
    CharSequence contentTitle;
    CharSequence contentText;
    PendingIntent contentIntent;
    // base intent for task stack
    final Intent showsIntent = new Intent(context, ShowsActivity.class);
    showsIntent.putExtra(ShowsActivity.InitBundle.SELECTED_TAB, ShowsActivity.InitBundle.INDEX_TAB_UPCOMING);
    final int count = notifyPositions.size();
    if (count == 1) {
        // notify in detail about one episode
        upcomingEpisodes.moveToPosition(notifyPositions.get(0));
        final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
        // show title and number, like 'Show 1x01'
        contentTitle = TextTools.getShowWithEpisodeNumber(this, showTitle, upcomingEpisodes.getInt(NotificationQuery.SEASON), upcomingEpisodes.getInt(NotificationQuery.NUMBER));
        tickerText = getString(R.string.upcoming_show, contentTitle);
        // "8:00 PM on Network"
        final String releaseTime = TimeTools.formatToLocalTime(this, TimeTools.applyUserOffset(this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
        final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
        contentText = getString(R.string.upcoming_show_detailed, releaseTime, network);
        Intent episodeDetailsIntent = new Intent(context, EpisodesActivity.class);
        episodeDetailsIntent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID));
        episodeDetailsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
        contentIntent = TaskStackBuilder.create(context).addNextIntent(showsIntent).addNextIntent(episodeDetailsIntent).getPendingIntent(REQUEST_CODE_SINGLE_EPISODE, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        // notify about multiple episodes
        tickerText = getString(R.string.upcoming_episodes);
        contentTitle = getString(R.string.upcoming_episodes_number, count);
        contentText = getString(R.string.upcoming_display);
        contentIntent = TaskStackBuilder.create(context).addNextIntent(showsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime)).getPendingIntent(REQUEST_CODE_MULTIPLE_EPISODES, PendingIntent.FLAG_CANCEL_CURRENT);
    }
    final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
    boolean richNotification = AndroidUtils.isJellyBeanOrHigher();
    if (richNotification) {
        // JELLY BEAN and above
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(nb, upcomingEpisodes.getString(NotificationQuery.POSTER));
            if (!DisplaySettings.preventSpoilers(context)) {
                final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE);
                final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW);
                final SpannableStringBuilder bigText = new SpannableStringBuilder();
                bigText.append(TextUtils.isEmpty(episodeTitle) ? "" : episodeTitle);
                bigText.setSpan(new StyleSpan(Typeface.BOLD), 0, bigText.length(), 0);
                bigText.append("\n");
                bigText.append(TextUtils.isEmpty(episodeSummary) ? "" : episodeSummary);
                nb.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText));
            }
            // Action button to check in
            Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class);
            checkInActionIntent.putExtra(QuickCheckInActivity.InitBundle.EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID));
            checkInActionIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
            checkInActionIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            PendingIntent checkInIntent = PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN, checkInActionIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent);
            // Action button to set watched
            Intent setWatchedIntent = new Intent(context, NotificationActionReceiver.class);
            setWatchedIntent.putExtra(NotificationActionReceiver.EXTRA_EPISODE_TVDBID, upcomingEpisodes.getInt(NotificationQuery._ID));
            // data to handle delete
            checkInActionIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
            PendingIntent setWatchedPendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE_ACTION_SET_WATCHED, setWatchedIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            nb.addAction(R.drawable.ic_action_tick, getString(R.string.action_watched), setWatchedPendingIntent);
            nb.setNumber(1);
        } else {
            // multiple episodes
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            // display at most the first five
            for (int displayIndex = 0; displayIndex < Math.min(count, 5); displayIndex++) {
                if (!upcomingEpisodes.moveToPosition(notifyPositions.get(displayIndex))) {
                    // could not go to the desired position (testing just in case)
                    break;
                }
                final SpannableStringBuilder lineText = new SpannableStringBuilder();
                // show title and number, like 'Show 1x01'
                String title = TextTools.getShowWithEpisodeNumber(this, upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE), upcomingEpisodes.getInt(NotificationQuery.SEASON), upcomingEpisodes.getInt(NotificationQuery.NUMBER));
                lineText.append(title);
                lineText.setSpan(new StyleSpan(Typeface.BOLD), 0, lineText.length(), 0);
                lineText.append(" ");
                // "8:00 PM on Network"
                String releaseTime = TimeTools.formatToLocalTime(this, TimeTools.applyUserOffset(this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
                String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
                lineText.append(getString(R.string.upcoming_show_detailed, releaseTime, network));
                inboxStyle.addLine(lineText);
            }
            // tell if we could not display all episodes
            if (count > 5) {
                inboxStyle.setSummaryText(getString(R.string.more, count - 5));
            }
            nb.setStyle(inboxStyle);
            nb.setNumber(count);
        }
    } else {
        // ICS and below
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(nb, upcomingEpisodes.getString(NotificationQuery.POSTER));
        }
    }
    // notification sound
    final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context);
    // If the string is empty, the user chose silent...
    boolean hasSound = ringtoneUri.length() != 0;
    if (hasSound) {
        // ...otherwise set the specified ringtone
        nb.setSound(Uri.parse(ringtoneUri));
    }
    // vibration
    boolean vibrates = NotificationSettings.isNotificationVibrating(context);
    if (vibrates) {
        nb.setVibrate(VIBRATION_PATTERN);
    }
    nb.setDefaults(Notification.DEFAULT_LIGHTS);
    nb.setWhen(System.currentTimeMillis());
    nb.setAutoCancel(true);
    nb.setTicker(tickerText);
    nb.setContentTitle(contentTitle);
    nb.setContentText(contentText);
    nb.setContentIntent(contentIntent);
    nb.setSmallIcon(R.drawable.ic_notification);
    nb.setColor(ContextCompat.getColor(this, R.color.accent_primary));
    nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);
    Intent i = new Intent(this, NotificationService.class);
    i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
    PendingIntent deleteIntent = PendingIntent.getService(this, REQUEST_CODE_DELETE_INTENT, i, PendingIntent.FLAG_CANCEL_CURRENT);
    nb.setDeleteIntent(deleteIntent);
    // build the notification
    Notification notification = nb.build();
    // use a unique id within the app
    NotificationManagerCompat nm = NotificationManagerCompat.from(getApplicationContext());
    nm.notify(SgApp.NOTIFICATION_EPISODE_ID, notification);
    Timber.d("Notification: count=%d, rich(JB+)=%s, sound=%s, vibrate=%s, delete=%d", count, richNotification ? "YES" : "NO", hasSound ? "YES" : "NO", vibrates ? "YES" : "NO", latestAirtime);
}
Also used : Context(android.content.Context) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) SpannableStringBuilder(android.text.SpannableStringBuilder) NotificationManagerCompat(android.support.v4.app.NotificationManagerCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) SuppressLint(android.annotation.SuppressLint) Notification(android.app.Notification) StyleSpan(android.text.style.StyleSpan) NotificationCompat(android.support.v4.app.NotificationCompat) PendingIntent(android.app.PendingIntent) SpannableStringBuilder(android.text.SpannableStringBuilder)

Aggregations

NotificationCompat (android.support.v4.app.NotificationCompat)13 PendingIntent (android.app.PendingIntent)11 Intent (android.content.Intent)8 NotificationManager (android.app.NotificationManager)6 TaskStackBuilder (android.support.v4.app.TaskStackBuilder)5 Bitmap (android.graphics.Bitmap)3 StyleSpan (android.text.style.StyleSpan)3 Notification (android.app.Notification)2 Cursor (android.database.Cursor)2 SpannableString (android.text.SpannableString)2 SpannableStringBuilder (android.text.SpannableStringBuilder)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 URL (java.net.URL)2 SuppressLint (android.annotation.SuppressLint)1 Context (android.content.Context)1 Resources (android.content.res.Resources)1 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)1 Drawable (android.graphics.drawable.Drawable)1 Location (android.location.Location)1