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.classiqo.nativeandroid_32bitz.MediaNotificationManager.java

private PendingIntent createContentIntent(MediaDescriptionCompat description) {
    Intent openUI = new Intent(mService, MusicPlayerActivity.class);
    openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    openUI.putExtra(MusicPlayerActivity.EXTRA_START_FULLSCREEN, true);

    if (description != null) {
        openUI.putExtra(MusicPlayerActivity.EXTRA_CURRENT_MEDIA_DESCRIPTION, description);
    }/*from   w w w  . j av a2  s.com*/

    return PendingIntent.getActivity(mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.conferenceengineer.android.iosched.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) {
    long currentTime;
    if (sessionStart < (currentTime = UIUtils.getCurrentTime(this)))
        return;//from  w  ww . j  a  va 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.conference_ic_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));
    }
    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.example.android.mediabrowserservice.MediaNotificationManager.java

private PendingIntent createContentIntent() {
    Intent openUI = new Intent(mService, MusicPlayerActivity.class);
    openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    return PendingIntent.getActivity(mService, REQUEST_CODE, openUI, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:net.helff.wificonnector.WifiConnectivityService.java

protected void sendNotification(String msg) {
    Log.i(TAG, "send notification: " + msg);
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.launchericon, msg, System.currentTimeMillis());

    Intent intent = new Intent(this, WifiConnectorActivity.class);
    intent.setAction("android.intent.action.MAIN");
    intent.addCategory("android.intent.category.LAUNCHER");
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    notification.setLatestEventInfo(this.getApplicationContext(), "WifiConnector", msg, pendingIntent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(1, notification);

}

From source file:com.sigilance.CardEdit.MainActivity.java

/**
 * Receive new NFC Intents to this activity only by enabling foreground dispatch.
 * This can only be done in onResume!/*from  w  w  w .ja va  2  s  .com*/
 */
public void enableNfcForegroundDispatch() {
    mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mNfcAdapter == null) {
        return;
    }
    Intent nfcI = new Intent(this, getClass())
            .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0, nfcI,
            PendingIntent.FLAG_CANCEL_CURRENT);
    IntentFilter[] writeTagFilters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) };

    try {
        mNfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, writeTagFilters, null);
    } catch (IllegalStateException e) {
        Toast.makeText(this, "NfcForegroundDispatch Error!", Toast.LENGTH_LONG).show();
    }
}

From source file:com.brq.wallet.lt.notification.GcmIntentService.java

private void showTradeNotification(String type, long lastChange) {
    Intent intent;/*w  w  w.j a v a2 s.  c  o m*/
    if (LtApi.TRADE_FINAL_NOTIFICATION_TYPE.equals(type)) {
        intent = LtMainActivity.createIntent(this, LtMainActivity.TAB_TYPE.TRADE_HISTORY);
    } else {
        intent = LtMainActivity.createIntent(this, LtMainActivity.TAB_TYPE.ACTIVE_TRADES);
    }

    Intent pinProtectedIntent = PinProtectedActivity.createIntent(this, intent);

    PendingIntent pIntent = PendingIntent.getActivity(this, 0, pinProtectedIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    String title = getResources().getString(R.string.lt_mycelium_local_trader_title);
    String message = getResources().getString(R.string.lt_new_trading_activity_message);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle(title)
            .setContentText(message).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pIntent)
            .setAutoCancel(true);

    // Add ticker
    builder.setTicker(message);

    // Tell other listeners that we have taken care of audibly notifying up
    // till this timestamp
    LocalTraderManager ltManager = MbwManager.getInstance(this).getLocalTraderManager();
    ltManager.setLastNotificationSoundTimestamp(lastChange);

    // Vibrate
    long[] pattern = { 500, 500 };
    builder.setVibrate(pattern);

    // Make a sound
    if (ltManager.getPlaySoundOnTradeNotification()) {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alarmSound != null) {
            builder.setSound(alarmSound);
        }
    }

    // Notify
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, builder.build());
}

From source file:com.mycelium.wallet.lt.notification.GcmIntentService.java

private void showTradeNotification(String type, long lastChange) {
    Intent intent;/* w  w w.j  ava  2  s  . c  om*/
    if (LtApi.TRADE_FINAL_NOTIFICATION_TYPE.equals(type)) {
        intent = LtMainActivity.createIntent(this, LtMainActivity.TAB_TYPE.TRADE_HISTORY);
    } else {
        intent = LtMainActivity.createIntent(this, LtMainActivity.TAB_TYPE.ACTIVE_TRADES);
    }

    Intent pinProtectedIntent = PinProtectedActivity.createIntent(this, intent);

    PendingIntent pIntent = PendingIntent.getActivity(this, 0, pinProtectedIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    String title = getResources().getString(R.string.lt_mycelium_local_trader_title);
    String message = getResources().getString(R.string.lt_new_trading_activity_message);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle(title)
            .setContentText(message).setSmallIcon(R.drawable.ic_launcher).setContentIntent(pIntent)
            .setAutoCancel(true);

    // Add ticker
    builder.setTicker(message);

    // Tell other listeners that we have taken care of audibly notifying up
    // till this timestamp
    LocalTraderManager ltManager = MbwManager.getInstance(this).getLocalTraderManager();
    ltManager.setLastNotificationSoundTimestamp(lastChange);

    // Vibrate
    long[] pattern = { 500, 500 };
    builder.setVibrate(pattern);

    // Make a sound
    if (ltManager.getPlaySoundOnTradeNotification()) {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alarmSound != null) {
            builder.setSound(alarmSound);
        }
    }

    // Notify
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, builder.build());
}

From source file:org.fdroid.fdroid.net.DownloaderService.java

public static PendingIntent createCancelDownloadIntent(@NonNull Context context, int requestCode,
        @NonNull String urlString) {
    Intent cancelIntent = new Intent(context.getApplicationContext(), DownloaderService.class)
            .setData(Uri.parse(urlString)).setAction(ACTION_CANCEL);
    return PendingIntent.getService(context.getApplicationContext(), requestCode, cancelIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.inovex.zabbixmobile.push.NotificationService.java

private void createNotification(String status, String message, Long triggerid) {
    int notIcon;//  w  w w  .  j  a  v  a  2  s  .  c om
    if (status != null && status.equals("OK")) {
        notIcon = R.drawable.ok;
    } else if (status != null && status.equals("PROBLEM")) {
        notIcon = R.drawable.problem;
    } else {
        notIcon = R.drawable.icon;
    }
    String tickerMessage;
    if (message != null && message.length() > 0) {
        tickerMessage = message;
    } else {
        return; // there is obviously no sensable message here
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(NotificationService.this);
    notificationBuilder.setTicker(tickerMessage);
    notificationBuilder.setWhen(System.currentTimeMillis());

    if (oldNotificationIcons) {
        notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
        notificationBuilder.setSmallIcon(notIcon);
    } else {
        notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), notIcon));
        notificationBuilder.setSmallIcon(R.drawable.icon);
    }

    // we do not start MainActivity directly, but
    // send a
    // broadcast which will be received by a
    // NotificationBroadcastReceiver which resets
    // the
    // notification status and starts MainActivity.
    Intent notificationIntent = new Intent();
    notificationIntent.setAction(ACTION_ZABBIX_NOTIFICATION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(NotificationService.this, uniqueRequestCode(),
            notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    notificationBuilder.setContentTitle(getResources().getString(R.string.notification_title));
    notificationBuilder.setContentText(message);
    notificationBuilder.setContentIntent(pendingIntent);
    notificationBuilder.setNumber(++numNotifications);

    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setOnlyAlertOnce(false);

    if (previousMessages.size() == NUM_STACKED_NOTIFICATIONS)
        previousMessages.poll();
    previousMessages.offer(message);
    // if there are several notifications, we stack
    // them in the
    // extended view
    if (numNotifications > 1) {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        // Sets a title for the Inbox style big view
        inboxStyle.setBigContentTitle(getResources().getString(R.string.notification_title));
        // Moves events into the big view
        for (CharSequence prevMessage : previousMessages) {
            inboxStyle.addLine(prevMessage);
        }
        if (numNotifications > NUM_STACKED_NOTIFICATIONS) {
            inboxStyle.setSummaryText((numNotifications - NUM_STACKED_NOTIFICATIONS) + " more");
        }
        // Moves the big view style object into the
        // notification
        // object.
        notificationBuilder.setStyle(inboxStyle);
    }

    if (status != null && status.equals("OK")) {
        if (okRingtone != null) {
            notificationBuilder.setSound(Uri.parse(okRingtone));
        }
    } else {
        if (ringtone != null) {
            notificationBuilder.setSound(Uri.parse(ringtone));
        }
    }

    Notification notification = notificationBuilder.build();

    Intent notificationDeleteIntent = new Intent();
    notificationDeleteIntent.setAction(ACTION_ZABBIX_NOTIFICATION_DELETE);
    notification.deleteIntent = PendingIntent.getBroadcast(NotificationService.this, 0,
            notificationDeleteIntent, 0);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // We use the same ID because we want to stack
    // the notifications and we don't really care
    // about the trigger ID anyway (clicking the
    // notification just starts the main activity).
    mNotificationManager.notify(0, notification);
}

From source file:org.interactiverobotics.headset_launcher.BluetoothHeadsetMonitorService.java

/**
 * @see BluetoothHeadsetMonitor.BluetoothHeadsetMonitorDelegate#onHeadsetConnected(String)
 *
 *///  w w w .j ava  2s .  c om
@Override
public void onHeadsetConnected(String name) {

    if (mCallbackMessengers.isEmpty()) {

        //  

        final Intent notificationIntent = new Intent(this, MainActivity.class);

        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.headset_launcher_notification).setContentTitle(name)
                .setContentText(getString(R.string.text_headset_connected)).setContentIntent(contentIntent)
                .setAutoCancel(true);

        final NotificationManager notificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1, builder.build());

        // ?  ?  ?

        mTimer.start();

    } else {

        //  

        final Bundle data = new Bundle();

        data.putString("ConnectedHeadsetName", name);

        for (Messenger x : mCallbackMessengers) {

            try {

                final Message message = Message.obtain(null, 3, 0, 0);

                message.setData(data);

                x.send(message);

            } catch (RemoteException e) {

                Log.e(TAG, "Callback error!");
            }
        }
    }
}