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.gdgdevfest.android.apps.devfestbcn.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) {
    long currentTime;
    if (sessionStart < (currentTime = UIUtils.getCurrentTime(this)))
        return;// w  w  w  .  j  a  v a 2  s .  co  m

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
        return;
    }

    final ContentResolver cr = getContentResolver();
    final Uri starredBlockUri = ScheduleContract.Blocks
            .buildStarredSessionsUri(ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
    Cursor c = cr.query(starredBlockUri, SessionDetailQuery.PROJECTION, null, null, null);
    int starredCount = 0;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    ArrayList<String> starredSessionRoomIds = new ArrayList<String>();
    String sessionId = null; // needed to get session track icon
    while (c.moveToNext()) {
        sessionId = c.getString(SessionDetailQuery.SESSION_ID);
        starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS);
        starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
        starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID));
    }
    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.
    PendingIntent pi = TaskStackBuilder.create(this).addNextIntent(new Intent(this, HomeActivity.class))
            .addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri))
            .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)
            .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 (starredCount == 1) {
        // get the track icon to show as the notification big picture
        Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId);
        Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION, null, null, null);
        if (tracksCursor.moveToFirst()) {
            String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME);
            int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR);
            Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(), trackName, trackColour);
            if (trackIcon != null) {
                notifBuilder.setLargeIcon(trackIcon);
            }
        }
    }
    if (minutesLeft > 5) {
        notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, sessionEnd, 5));
    }
    if (starredCount == 1 && PrefUtils.isAttendeeAtVenue(this)) {
        notifBuilder.addAction(R.drawable.ic_map_holo_dark, res.getString(R.string.title_map),
                createRoomMapIntent(starredSessionRoomIds.get(0)));
    }
    NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
            .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount));

    // 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);
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

From source file:com.sean.takeastand.alarmprocess.ScheduledRepeatingAlarm.java

private PendingIntent createPendingIntent(Context context, FixedAlarmSchedule alarmSchedule) {
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(Constants.ALARM_SCHEDULE, alarmSchedule);
    return PendingIntent.getBroadcast(context, REPEATING_ALARM_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.keepassdroid.EntryActivity.java

private Notification getNotification(String intentText, int descResId) {
    String desc = getString(descResId);

    Intent intent = new Intent(intentText);
    PendingIntent pending = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // no longer supported for api level >22
    // notify.setLatestEventInfo(this, getString(R.string.app_name), desc, pending);
    // so instead using compat builder and create new notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotificationUtil.COPY_CHANNEL_ID);
    Notification notify = builder.setContentIntent(pending).setContentText(desc)
            .setContentTitle(getString(R.string.app_name)).setSmallIcon(R.drawable.notify).setTicker(desc)
            .setWhen(System.currentTimeMillis()).build();

    return notify;
}

From source file:org.opensilk.music.ui2.LauncherActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Timber.v("onActivityResult");
    switch (requestCode) {
    case StartActivityForResult.APP_REQUEST_SETTINGS:
        switch (resultCode) {
        case ActivityResult.RESULT_RESTART_APP:
            // Hack to force a refresh for our activity for eg theme change
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
            PendingIntent pi = PendingIntent.getActivity(this, 0, getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage(getBaseContext().getPackageName()),
                    PendingIntent.FLAG_CANCEL_CURRENT);
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 700, pi);
            finish();/*from w  w  w. j  a va 2  s  . co m*/
            break;
        case ActivityResult.RESULT_RESTART_FULL:
            killServiceOnExit = true;
            onActivityResult(StartActivityForResult.APP_REQUEST_SETTINGS, ActivityResult.RESULT_RESTART_APP,
                    data);
            break;
        }
        break;
    case StartActivityForResult.PLUGIN_REQUEST_LIBRARY:
    case StartActivityForResult.PLUGIN_REQUEST_SETTINGS:
        mBus.post(new ActivityResult(data, requestCode, resultCode));
        break;
    default:
        super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:org.tunesremote.util.NotificationService.java

@Override
public void onCreate() {
    super.onCreate();

    nHelper = new NotificationHelper(this);

    // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    ////from  w  w w.j  a va2s  . c o  m
    // // Sets up the lockscreen stuff
    // AudioManager am = (AudioManager)
    // getSystemService(Context.AUDIO_SERVICE);
    // am.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
    // AudioManager.AUDIOFOCUS_GAIN);
    // ComponentName lockscreenRec = new ComponentName(this,
    // LockscreenReceiver.class);
    // am.registerMediaButtonEventReceiver(lockscreenRec);
    //
    // Intent broadcast = new
    // Intent(Intent.ACTION_MEDIA_BUTTON).setComponent(lockscreenRec);
    // PendingIntent broadPender = PendingIntent.getBroadcast(this, 0,
    // broadcast, PendingIntent.FLAG_UPDATE_CURRENT);
    //
    // rcc = new RemoteControlClient(broadPender);
    // rcc.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_NEXT |
    // RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE);
    // am.registerRemoteControlClient(rcc);
    //
    // }

    bindService(new Intent(this, BackendService.class), connection, BIND_AUTO_CREATE);

    endServiceIntent = new Intent(this, NotificationService.class).setAction(ACTION_END_SERVICE);
    pauseIntent = new Intent(this, NotificationService.class).setAction(ACTION_PAUSE);
    nextTrackIntent = new Intent(this, NotificationService.class).setAction(ACTION_NEXT_TRACK);
    launchIntent = new Intent(this, ControlActivity.class);

    endServicePending = PendingIntent.getService(this, 0, endServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    pausePending = PendingIntent.getService(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    nextTrackPending = PendingIntent.getService(this, 0, nextTrackIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    launchPending = PendingIntent.getActivity(this, 0, launchIntent, PendingIntent.FLAG_CANCEL_CURRENT);

}

From source file:ca.zadrox.dota2esportticker.service.ReminderAlarmService.java

private void notifyMatch(long matchId) {
    if (!PrefUtils.shouldShowMatchReminders(this)) {
        return;//  w  w  w .j a  v  a  2 s  .c o  m
    }

    final ContentResolver cr = getContentResolver();

    Cursor c = cr.query(MatchContract.SeriesEntry.CONTENT_URI, MatchDetailQuery.PROJECTION,
            SESSION_ID_WHERE_CLAUSE, new String[] { String.valueOf(matchId) }, null);

    if (!c.moveToNext()) {
        return;
    }

    Intent baseIntent = new Intent(this, MatchActivity.class);
    baseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

    Intent matchIntent = new Intent(this, MatchDetailActivity.class);
    matchIntent.putExtra(MatchDetailActivity.ARGS_GG_MATCH_ID, matchId);
    taskBuilder.addNextIntent(matchIntent);

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

    final Resources res = getResources();
    String contentTitle = c.getString(MatchDetailQuery.TEAM_ONE_NAME) + " vs "
            + c.getString(MatchDetailQuery.TEAM_TWO_NAME);

    String contentText;

    long currentTime = TimeUtils.getUTCTime();
    long matchStart = c.getLong(MatchDetailQuery.DATE_TIME);

    int minutesLeft = (int) (matchStart - currentTime + 59000) / 60000;
    if (minutesLeft < 2 && minutesLeft >= 0) {
        minutesLeft = 1;
    }

    if (minutesLeft < 0) {
        contentText = "is scheduled to start now. (" + c.getString(MatchDetailQuery.TOURNAMENT_NAME) + ")";
    } else {
        contentText = "is scheduled to start in " + minutesLeft + " min. ("
                + c.getString(MatchDetailQuery.TOURNAMENT_NAME) + ")";
    }

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this).setContentTitle(contentTitle)
            .setContentText(contentText).setColor(res.getColor(R.color.theme_primary))
            .setTicker(contentTitle + " is about to start.")
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setLights(NOTIFICATION_ARGB_COLOR, NOTIFICATION_LED_ON_MS, NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(R.drawable.ic_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_DEFAULT).setAutoCancel(true);

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    nm.notify(NOTIFICATION_ID, notifBuilder.build());
}

From source file:org.ciasaboark.tacere.manager.NotificationManagerWrapper.java

/**
 * Builds and displays a notification for the given CalEvent. This method uses the new
 * Notification API to place an action button in the notification.
 *
 * @param event the CalEvent that is currently active
 *///from w  w w.ja  va 2  s.c o m
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void displayNewEventNotification(EventInstance event) {
    // clicking the notification should take the user to the app
    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // FLAG_CANCEL_CURRENT is required to make sure that the extras are including in
    // the new pending intent
    PendingIntent pendIntent = PendingIntent.getActivity(context, REQUEST_CODES.EVENT_OPEN_MAIN,
            notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    Notification.Builder notBuilder = new Notification.Builder(context)
            .setContentTitle(context.getString(R.string.notification_event_active_title))
            .setContentText(event.toString()).setAutoCancel(false).setOnlyAlertOnce(true).setOngoing(true)
            .setContentIntent(pendIntent);

    EventManager eventManager = new EventManager(context, event);
    switch (eventManager.getBestRinger()) {
    case SILENT:
        notBuilder.setSmallIcon(R.drawable.not_silence);
        break;
    case VIBRATE:
        notBuilder.setSmallIcon(R.drawable.not_vibrate);
        break;
    case NORMAL:
        notBuilder.setSmallIcon(R.drawable.not_normal);
        break;
    }

    // this intent will be attached to the button on the notification
    Intent skipEventIntent = new Intent(context, SkipEventService.class);
    skipEventIntent.putExtra(SkipEventService.EVENT_ID_TAG, event.getId());
    PendingIntent skipEventPendIntent = PendingIntent.getService(context, REQUEST_CODES.EVENT_IGNORE,
            skipEventIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    notBuilder.addAction(R.drawable.not_ignore, context.getString(R.string.notification_event_skip),
            skipEventPendIntent);

    //an intent to add an additional 15 minutes of silencing for an event
    Intent addSilencingIntent = new Intent(context, ExtendEventService.class);
    addSilencingIntent.putExtra(ExtendEventService.INSTANCE_ID, event.getId());
    addSilencingIntent.putExtra(ExtendEventService.NEW_EXTEND_LENGTH, event.getExtendMinutes() + 15); //TODO use minutes stored in prefs
    PendingIntent addSilenceingPendIntent = PendingIntent.getService(context, REQUEST_CODES.EVENT_ADD_TIME,
            addSilencingIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    Authenticator authenticator = new Authenticator(context);
    if (authenticator.isAuthenticated()) {
        notBuilder.addAction(R.drawable.not_clock, "+15", addSilenceingPendIntent);
    }

    // the ticker text should only be shown the first time the notification is
    // created, not on each update
    notBuilder
            .setTicker(context.getString(R.string.notification_event_active_starting) + " " + event.toString());

    if (Build.VERSION.SDK_INT >= 21) {
        notBuilder.setVisibility(Notification.VISIBILITY_PRIVATE);
        Notification.Builder publicNotification = getBaseEventNotificationBuilder();
        publicNotification.setContentTitle(context.getString(R.string.notification_event_active_title_public));
        publicNotification.setContentIntent(pendIntent);
        notBuilder.setPublicVersion(publicNotification.build());
        notBuilder.setColor(context.getResources().getColor(R.color.accent));

        Drawable d = context.getResources().getDrawable(R.drawable.shape_circle);
        int height = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_height);
        int width = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_width);
        d.setBounds(0, 0, width, height);
        d.mutate().setColorFilter(event.getDisplayColor(), PorterDuff.Mode.MULTIPLY);
        DatabaseInterface databaseInterface = DatabaseInterface.getInstance(context);
        String calendarTitle = databaseInterface.getCalendarNameForId(event.getCalendarId());
        String c = "";
        if (calendarTitle != null && calendarTitle != "") {
            c = ((Character) calendarTitle.charAt(0)).toString().toUpperCase();
        }

        Bitmap largeIcon = createMarkerIcon(d, c, width, height);
        //            Bitmap largeIcon = combineDrawablesToBitmap(d, getRingerIconForEvent(event), width, height);
        notBuilder.setLargeIcon(largeIcon);
    }

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, notBuilder.build());
}

From source file:org.numixproject.hermes.irc.IRCService.java

/**
 * Handle command//from ww w  .  j  av  a2 s .  c om
 *
 * @param intent
 */
private void handleCommand(Intent intent) {
    if (ACTION_FOREGROUND.equals(intent.getAction())) {
        if (foreground) {
            return; // XXX: We are already in foreground...
        }
        foreground = true;

        Intent disconnect = new Intent("disconnect_all");
        PendingIntent pendingIntentDisconnect = PendingIntent.getBroadcast(this, 0, disconnect,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentText(getText(R.string.notification_running));
        builder.setSmallIcon(R.drawable.ic_stat_hermes2);
        builder.setWhen(System.currentTimeMillis());
        builder.addAction(R.drawable.ic_action_ic_close_24px, "DISCONNECT ALL", pendingIntentDisconnect);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setColor(Color.parseColor("#0097A7"));
        }

        // The PendingIntent to launch our activity if the user selects this notification
        Intent notifyIntent = new Intent(this, MainActivity.class);
        notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);

        // Set the info for the views that show in the notification panel.
        builder.setContentIntent(contentIntent).setWhen(System.currentTimeMillis())
                .setContentTitle(getText(R.string.app_name))
                .setContentText(getText(R.string.notification_not_connected));
        Notification notification = builder.build();

        startForegroundCompat(FOREGROUND_NOTIFICATION, notification);
    } else if (ACTION_BACKGROUND.equals(intent.getAction()) && !foreground) {
        stopForegroundCompat(FOREGROUND_NOTIFICATION);
    } else if (ACTION_ACK_NEW_MENTIONS.equals(intent.getAction())) {
        ackNewMentions(intent.getIntExtra(EXTRA_ACK_SERVERID, -1), intent.getStringExtra(EXTRA_ACK_CONVTITLE));
    }
}

From source file:net.kourlas.voipms_sms.notifications.Notifications.java

/**
 * Shows a notification with the specified details.
 *
 * @param contact   The contact that the notification is from.
 * @param shortText The short form of the message text.
 * @param longText  The long form of the message text.
 *//* ww w  . j  av a 2s . co m*/
private void showNotification(String contact, String shortText, String longText) {

    String title = Utils.getContactName(applicationContext, contact);
    if (title == null) {
        title = Utils.getFormattedPhoneNumber(contact);
    }
    NotificationCompat.Builder notification = new NotificationCompat.Builder(applicationContext);
    notification.setContentTitle(title);
    notification.setContentText(shortText);
    notification.setSmallIcon(R.drawable.ic_chat_white_24dp);
    notification.setPriority(Notification.PRIORITY_HIGH);
    String notificationSound = Preferences.getInstance(applicationContext).getNotificationSound();
    if (!notificationSound.equals("")) {
        notification.setSound(Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
    }
    String num = Utils.getFormattedPhoneNumber(contact);
    Log.v("prior", num);

    SharedPreferences sharedPreferences = applicationContext.getSharedPreferences("ledData",
            Context.MODE_PRIVATE);
    String cNm = sharedPreferences.getString(title, "3000");
    SharedPreferences sharedPref = applicationContext.getSharedPreferences("color", Context.MODE_PRIVATE);
    int clr = sharedPref.getInt(title, 0xFF02ffff);
    Log.v("saved rate of ", cNm + " for " + title);
    int ledSpeed = 3000;
    int color = 0xFF02ffff;

    if (cNm.equals("500") || cNm.equals("3000")) {
        ledSpeed = Integer.parseInt(cNm);
        color = clr;
    }

    notification.setLights(color, ledSpeed, ledSpeed);

    if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
        notification.setVibrate(new long[] { 0, 250, 250, 250 });
    } else {
        notification.setVibrate(new long[] { 0 });
    }
    notification.setColor(0xFF546e7a);
    notification.setAutoCancel(true);
    notification.setStyle(new NotificationCompat.BigTextStyle().bigText(longText));

    Bitmap largeIconBitmap;
    try {
        largeIconBitmap = MediaStore.Images.Media.getBitmap(applicationContext.getContentResolver(),
                Uri.parse(Utils.getContactPhotoUri(applicationContext, contact)));
        largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
        largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
        notification.setLargeIcon(largeIconBitmap);
    } catch (Exception ignored) {
        // Do nothing.
    }

    Intent intent = new Intent(applicationContext, ConversationActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(applicationContext.getString(R.string.conversation_extra_contact), contact);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
    stackBuilder.addParentStack(ConversationActivity.class);
    stackBuilder.addNextIntent(intent);
    notification.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

    Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
    } else {
        //noinspection deprecation
        replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
    }
    replyIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact), contact);
    PendingIntent replyPendingIntent = PendingIntent.getActivity(applicationContext, 0, replyIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_reply_white_24dp, applicationContext.getString(R.string.notifications_button_reply),
            replyPendingIntent);
    notification.addAction(replyAction.build());

    Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
    markAsReadIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact), contact);
    PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast(applicationContext, 0, markAsReadIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_drafts_white_24dp,
            applicationContext.getString(R.string.notifications_button_mark_read), markAsReadPendingIntent);
    notification.addAction(markAsReadAction.build());

    int id;
    if (notificationIds.get(contact) != null) {
        id = notificationIds.get(contact);
    } else {
        id = notificationIdCount++;
        notificationIds.put(contact, id);
    }
    NotificationManager notificationManager = (NotificationManager) applicationContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(id, notification.build());
}

From source file:org.sufficientlysecure.keychain.service.PassphraseCacheService.java

/**
 * Build pending intent that is executed by alarm manager to time out a specific passphrase
 *
 * @param context/*from   ww w  .  j  a  va  2 s  . c  o  m*/
 * @param keyId
 * @return
 */
private static PendingIntent buildIntent(Context context, long keyId) {
    Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE);
    intent.putExtra(EXTRA_KEY_ID, keyId);
    PendingIntent sender = PendingIntent.getBroadcast(context, REQUEST_ID, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    return sender;
}