Example usage for android.app PendingIntent FLAG_CANCEL_CURRENT

List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT

Introduction

In this page you can find the example usage for android.app PendingIntent FLAG_CANCEL_CURRENT.

Prototype

int FLAG_CANCEL_CURRENT

To view the source code for android.app PendingIntent FLAG_CANCEL_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

Usage

From source file:com.sonetel.service.SipNotifications.java

public void showNotificationForMessage(SipMessage msg) {
    if (!CustomDistribution.supportMessaging()) {
        return;//from  ww  w .j  a va2s  .c  o  m
    }
    // CharSequence tickerText = context.getText(R.string.instance_message);
    if (!msg.getFrom().equalsIgnoreCase(viewingRemoteFrom)) {
        String from = formatRemoteContactString(msg.getFullFrom());
        if (from.equalsIgnoreCase(msg.getFullFrom())) {
            from = msg.getDisplayName() + " " + from;
        }
        CharSequence tickerText = buildTickerMessage(context, from, msg.getBody());

        if (messageNotification == null) {
            messageNotification = new NotificationCompat.Builder(context);
            messageNotification.setSmallIcon(SipUri.isPhoneNumber(from) ? R.drawable.stat_notify_sms
                    : android.R.drawable.stat_notify_chat);
            messageNotification.setTicker(tickerText);
            messageNotification.setWhen(System.currentTimeMillis());
            messageNotification.setDefaults(Notification.DEFAULT_ALL);
            messageNotification.setAutoCancel(true);
            messageNotification.setOnlyAlertOnce(true);
        }

        Intent notificationIntent = new Intent(SipManager.ACTION_SIP_MESSAGES);
        notificationIntent.putExtra(SipMessage.FIELD_FROM, msg.getFrom());
        notificationIntent.putExtra(SipMessage.FIELD_BODY, msg.getBody());
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        messageNotification.setContentTitle(from);
        messageNotification.setContentText(msg.getBody());
        messageNotification.setContentIntent(contentIntent);

        notificationManager.notify(MESSAGE_NOTIF_ID, messageNotification.getNotification());
    }
}

From source file:org.thoughtcrime.SMP.notifications.MessageNotifier.java

private static void scheduleReminder(Context context, MasterSecret masterSecret, int count) {
    if (count >= TextSecurePreferences.getRepeatAlertsCount(context)) {
        return;/*from w  ww .  j a  v a  2 s.  c om*/
    }

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION);
    alarmIntent.putExtra("reminder_count", count);

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    long timeout = TimeUnit.MINUTES.toMillis(2);

    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeout, pendingIntent);
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static void showNotificationAtReminderTime(Context context, String title, String note) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true).setContentTitle(title)
            .setContentText(note);/*w ww  .java 2s.c om*/
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    builder.setSound(alarmSound);

    Intent resultIntent = new Intent(context, ActivityHome.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(ActivityHome.class);
    stackBuilder.addNextIntent(resultIntent);

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(resultPendingIntent);

    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, builder.build());
}

From source file:org.thoughtcrime.SMP.notifications.MessageNotifier.java

private static void clearReminder(Context context) {
    Intent alarmIntent = new Intent(ReminderReceiver.REMINDER_ACTION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);//ww  w  .j a  va 2 s  .co m
}

From source file:org.adaway.service.ApplyService.java

/**
 * Creates custom made notification with progress
 *//*from ww w . jav  a 2s . co m*/
private void showApplyNotification(Context context, String tickerText, String contentTitle,
        String contentText) {
    // configure the intent
    Intent intent = new Intent(mService, BaseActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(mService.getApplicationContext(), 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    // add app name to notificationText
    tickerText = mService.getString(R.string.app_name) + ": " + tickerText;
    int icon = R.drawable.status_bar_icon;
    long when = System.currentTimeMillis();

    // add app name to title
    String contentTitleWithAppName = mService.getString(R.string.app_name) + ": " + contentTitle;

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(icon)
            .setContentTitle(contentTitleWithAppName).setTicker(tickerText).setWhen(when).setOngoing(true)
            .setOnlyAlertOnce(true).setContentText(contentText);

    mNotificationManager.notify(APPLY_NOTIFICATION_ID, mBuilder.build());

    mBuilder.setContentIntent(contentIntent);

    // update status in BaseActivity with Broadcast
    BaseActivity.setStatusBroadcast(mService, contentTitle, contentText, StatusCodes.CHECKING);
}

From source file:com.ubergeek42.WeechatAndroid.service.RelayServiceBackbone.java

@TargetApi(19)
void schedulePing(long triggerAt, Bundle extras) {
    Intent intent = new Intent(PingActionReceiver.PING_ACTION);
    intent.putExtras(extras);//from   w ww . j ava  2 s .  c  o  m

    PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmMgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, alarmIntent);
    } else {
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAt, alarmIntent);
    }
}

From source file:com.jjcamera.apps.iosched.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LOGD(TAG, "Considering notifying for time interval.");
    LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;/* w  ww  .j ava  2  s  .c o  m*/
    }

    if (!SettingsUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = null;
    try {
        c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
                ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
                ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
        int starredCount = c.getCount();
        LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
        String singleSessionId = null;
        String singleSessionRoomId = null;
        ArrayList<String> starredSessionTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
            singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
            starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
            LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
        }
        if (starredCount < 1) {
            return;
        }

        // Generates the pending intent which gets fired when the user taps on the notification.
        // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
        // related to navigation from notifications.
        Intent baseIntent = new Intent(this, MyScheduleActivity.class);
        baseIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

        // For a single session, tapping the notification should open the session details (b/15350787)
        if (starredCount == 1) {
            taskBuilder.addNextIntent(
                    new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
        }

        PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

        final Resources res = getResources();
        String contentText;
        int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
        if (minutesLeft < 1) {
            minutesLeft = 1;
        }

        if (starredCount == 1) {
            contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
        } else {
            contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1,
                    minutesLeft, starredCount - 1);
        }

        NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
                .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
                .setColor(getResources().getColor(R.color.theme_primary))
                .setTicker(res
                        .getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
                .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
                .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR,
                        SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS)
                .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
                .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
        if (minutesLeft > 5) {
            notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                    String.format(res.getString(R.string.snooze_x_min), 5),
                    createSnoozeIntent(sessionStart, intervalEnd, 5));
        }
        /*if (starredCount == 1 && SettingsUtils.isAttendeeAtVenue(this)) {
        notifBuilder.addAction(R.drawable.ic_map_holo_dark,
                res.getString(R.string.title_map),
                createRoomMapIntent(singleSessionRoomId));
        }*/
        String bigContentTitle;
        if (starredCount == 1 && starredSessionTitles.size() > 0) {
            bigContentTitle = starredSessionTitles.get(0);
        } else {
            bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount);
        }
        NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
                .setBigContentTitle(bigContentTitle);

        // Adds starred sessions starting at this time block to the notification.
        for (int i = 0; i < starredCount; i++) {
            richNotification.addLine(starredSessionTitles.get(i));
        }
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        LOGD(TAG, "Now showing notification.");
        nm.notify(NOTIFICATION_ID, richNotification.build());
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.chen.mail.utils.NotificationActionUtils.java

public static Notification createUndoNotification(final Context context,
        final NotificationAction notificationAction, final int notificationId) {
    LogUtils.i(LOG_TAG, "createUndoNotification for %s", notificationAction.getNotificationActionType());

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

    builder.setSmallIcon(R.drawable.stat_notify_email);
    builder.setWhen(notificationAction.getWhen());

    final RemoteViews undoView = new RemoteViews(context.getPackageName(), R.layout.undo_notification);
    undoView.setTextViewText(R.id.description_text, context.getString(notificationAction.getActionTextResId()));

    final String packageName = context.getPackageName();

    final Intent clickIntent = new Intent(NotificationActionIntentService.ACTION_UNDO);
    clickIntent.setPackage(packageName);
    putNotificationActionExtra(clickIntent, notificationAction);
    final PendingIntent clickPendingIntent = PendingIntent.getService(context, notificationId, clickIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    undoView.setOnClickPendingIntent(R.id.status_bar_latest_event_content, clickPendingIntent);

    builder.setContent(undoView);/*from w w  w .ja va  2  s .c  o m*/

    // When the notification is cleared, we perform the destructive action
    final Intent deleteIntent = new Intent(NotificationActionIntentService.ACTION_DESTRUCT);
    deleteIntent.setPackage(packageName);
    putNotificationActionExtra(deleteIntent, notificationAction);
    final PendingIntent deletePendingIntent = PendingIntent.getService(context, notificationId, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setDeleteIntent(deletePendingIntent);

    final Notification notification = builder.build();

    return notification;
}

From source file:org.chromium.chrome.browser.physicalweb.UrlManager.java

private PendingIntent createClearNotificationAlarmIntent() {
    Intent intent = new Intent(mContext, ClearNotificationAlarmReceiver.class);
    return PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}