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.android.example.alwaysonstopwatch.StopwatchActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stopwatch);

    // Enable Ambient Mode
    setAmbientEnabled();/* w ww. j  av  a  2 s.  c  o  m*/

    mAmbientStateAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // Create pending intent
    Intent intent = new Intent(getApplicationContext(), StopwatchActivity.class);
    mAmbientStatePendingIntent = PendingIntent.getActivity(getApplicationContext(), R.id.msg_update, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    // Get on screen items
    mStartStopButton = (Button) findViewById(R.id.startstopbtn);
    mResetButton = (Button) findViewById(R.id.resetbtn);
    mTimeView = (TextView) findViewById(R.id.timeview);
    resetTimeView(); // initialise TimeView

    mBackground = findViewById(R.id.gridbackground);
    mClockView = (TextClock) findViewById(R.id.clock);
    mNotice = (TextView) findViewById(R.id.notice);
    mNotice.getPaint().setAntiAlias(false);
    mActiveBackgroundColor = ContextCompat.getColor(this, R.color.activeBackground);
    mActiveForegroundColor = ContextCompat.getColor(this, R.color.activeText);

    mStartStopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, "Toggle start / stop state");
            toggleStartStop();
        }
    });

    mResetButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, "Reset time");
            mLastTick = 0L;
            mTimeSoFar = 0L;
            resetTimeView();
        }
    });

    mActiveClockUpdateHandler.sendEmptyMessage(R.id.msg_update);
}

From source file:org.liberty.android.fantastischmemo.service.AnyMemoService.java

@SuppressWarnings("deprecation")
private void showNotification() {
    try {/*from   w w  w .j  a v  a  2  s.  co  m*/
        DatabaseInfo dbInfo = new DatabaseInfo(this);
        if (dbInfo.getRevCount() < 10) {
            return;
        }
        Intent myIntent = new Intent(this, AnyMemo.class);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = new Notification(R.drawable.anymemo_notification_icon,
                getString(R.string.app_name), System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        PendingIntent pIntent = PendingIntent.getActivity(this, NOTIFICATION_REQ, myIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setLatestEventInfo(this, dbInfo.getDbName(),
                getString(R.string.stat_scheduled) + " " + dbInfo.getRevCount(), pIntent);

        notificationManager.notify(NOTIFICATION_ID, notification);
        Log.v(TAG, "Notification Invoked!");
    } catch (Exception e) {
        /* Do not show notification when AnyMemo can not
         * fetch the into
         */
    }
}

From source file:de.ub0r.android.portaltimer.UpdateReceiver.java

private boolean updateNotification(final Context context) {
    Log.d(TAG, "updateNotification()");
    lastUpdate = System.currentTimeMillis();
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    ArrayList<Timer> timers = new ArrayList<Timer>();
    mNow = System.currentTimeMillis();
    mNextTarget = 0;//from w  w w .  j ava  2  s  .c o m
    boolean alert = false;
    Log.d(TAG, "mNow: " + mNow);

    for (int j = 0; j < Timer.TIMER_IDS.length; j++) {
        Timer t = new Timer(context, j);
        timers.add(t);
        long tt = t.getTarget();
        Log.d(TAG, "target(" + j + "): " + tt);

        if (tt > 0) {
            if (mNextTarget == 0 || tt < mNextTarget) {
                mNextTarget = tt;
            }
            if (tt < mNow) {
                alert = true;
                t.reset(context);
            }
        }
    }
    Log.d(TAG, "mNextTarget: " + mNextTarget);

    NotificationCompat.Builder b = new NotificationCompat.Builder(context);
    b.setPriority(1000);
    Intent i = new Intent(context, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    b.setContentIntent(PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT));

    b.setContentTitle(context.getString(R.string.app_name));
    b.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher));
    b.setSmallIcon(R.drawable.ic_stat_timer);
    b.setAutoCancel(false);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { // GB-
        b.setContentText(context.getString(R.string.notification_text, timers.get(0).getFormatted(),
                timers.get(1).getFormatted(), timers.get(2).getFormatted()));
    } else { // HC+
        RemoteViews v = new RemoteViews(context.getPackageName(), R.layout.notification);
        for (int j = 0; j < Timer.TIMER_IDS.length; j++) {
            v.setTextViewText(Timer.TIMER_IDS[j], timers.get(j).getFormatted().toString());
            Intent ij = new Intent(Timer.TIMER_KEYS[j], null, context, UpdateReceiver.class);
            v.setOnClickPendingIntent(Timer.TIMER_IDS[j],
                    PendingIntent.getBroadcast(context, 0, ij, PendingIntent.FLAG_UPDATE_CURRENT));
        }
        v.setOnClickPendingIntent(R.id.settings, PendingIntent.getActivity(context, 0,
                new Intent(context, SettingsActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
        b.setContent(v);
    }

    if (mNextTarget <= 0 && !alert) {
        // we don't need any notification
        b.setOngoing(false);
        nm.notify(0, b.build());
        return false;
    } else if (alert) {
        // show notification without running Timer
        b.setOngoing(mNextTarget > 0);
        SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
        if (p.getBoolean("vibrate", true)) {
            b.setVibrate(VIBRATE);
        }
        String n = p.getString("notification", null);
        if (n == null) { // default
            b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        } else if (n.length() > 1) {
            try {
                b.setSound(Uri.parse(n));
            } catch (Exception e) {
                Log.e(TAG, "invalid notification uri", e);
                b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            }
        } // else: silent
        nm.notify(0, b.build());
        return true;
    } else {
        // show notification with running Timer
        b.setOngoing(true);
        nm.notify(0, b.build());
        return true;
    }
}

From source file:it.uniroma2.foundme.studente.GcmIntentService.java

private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    data = extractData(msg);/*from  w  w w.  j  av a  2 s.  c o  m*/

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, CourseActivity.class).putExtra("Corso", data), PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setContentTitle("FoundMe")
            .setSmallIcon(R.drawable.ic_launcher).setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))//imposta il suono
            .setAutoCancel(true).setOngoing(true).setLights(Color.BLUE, 1000, 1000)// imposta il led
    ;
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

From source file:com.meiste.greg.ptw.RaceAlarm.java

@Override
protected void onHandleIntent(final Intent intent) {
    alarm_set = false;/*from w  w  w . j  a  v a  2  s  . c o m*/
    final Race race = Race.getInstance(this, intent.getIntExtra(RACE_ID, 0));
    Util.log("Received race alarm for race " + race.getId());

    synchronized (mSync) {
        if (mContainer == null) {
            try {
                mSync.wait();
            } catch (final InterruptedException e) {
            }
        }
    }

    // Only show notification if user wants race reminders
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getBoolean(EditPreferences.KEY_NOTIFY_RACE, true)
            && mContainer.getBoolean(GtmHelper.KEY_GAME_ENABLED)) {
        final Intent notificationIntent = new Intent(this, RaceActivity.class);
        notificationIntent.putExtra(RaceActivity.INTENT_ID, race.getId());
        notificationIntent.putExtra(RaceActivity.INTENT_ALARM, true);
        final PendingIntent pi = PendingIntent.getActivity(this, PI_REQ_CODE, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        int defaults = 0;
        if (prefs.getBoolean(EditPreferences.KEY_NOTIFY_VIBRATE, true))
            defaults |= Notification.DEFAULT_VIBRATE;
        if (prefs.getBoolean(EditPreferences.KEY_NOTIFY_LED, true))
            defaults |= Notification.DEFAULT_LIGHTS;

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_steering_wheel)
                .setTicker(getString(R.string.remind_race_ticker, race.getName()))
                .setContentTitle(getString(R.string.remind_race_notify)).setContentText(race.getName())
                .setContentIntent(pi).setAutoCancel(true).setDefaults(defaults).setSound(Uri
                        .parse(prefs.getString(EditPreferences.KEY_NOTIFY_RINGTONE, PTW.DEFAULT_NOTIFY_SND)));

        getNM(this).notify(R.string.remind_race_ticker, builder.build());
    } else {
        Util.log("Ignoring race alarm since option is disabled");
    }

    // Reset alarm for the next race
    set(this);
    sendBroadcast(new Intent(PTW.INTENT_ACTION_RACE_ALARM));
}

From source file:com.philliphsu.clock2.alarms.background.UpcomingAlarmReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final byte[] alarmBytes = intent.getByteArrayExtra(EXTRA_ALARM);
    // Unmarshall the bytes into a parcel and create our Alarm with it.
    final Alarm alarm = ParcelableUtil.unmarshall(alarmBytes, Alarm.CREATOR);
    if (alarm == null) {
        throw new IllegalStateException("No alarm received");
    }//w  w w. ja v  a 2s . c  om

    final long id = alarm.getId();
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final boolean actionShowSnoozing = ACTION_SHOW_SNOOZING.equals(intent.getAction());
    if (intent.getAction() == null || actionShowSnoozing) {
        // Prepare notification
        // http://stackoverflow.com/a/15803726/5055032
        // Notifications aren't updated on the UI thread, so we could have
        // done this in the background. However, no lengthy operations are
        // done here, so doing so is a premature optimization.
        String title;
        String text;
        if (actionShowSnoozing) {
            if (!alarm.isSnoozed()) {
                throw new IllegalStateException("Can't show snoozing notif. if alarm not snoozed!");
            }
            title = alarm.label().isEmpty() ? context.getString(R.string.alarm) : alarm.label();
            text = context.getString(R.string.title_snoozing_until, formatTime(context, alarm.snoozingUntil()));
        } else {
            // No intent action required for default behavior
            title = context.getString(R.string.upcoming_alarm);
            text = formatTime(context, alarm.ringsAt());
            if (!alarm.label().isEmpty()) {
                text = alarm.label() + ", " + text;
            }
        }

        Intent dismissIntent = new Intent(context, UpcomingAlarmReceiver.class).setAction(ACTION_DISMISS_NOW)
                .putExtra(EXTRA_ALARM, ParcelableUtil.marshall(alarm));
        PendingIntent piDismiss = PendingIntent.getBroadcast(context, (int) id, dismissIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification note = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_alarm_24dp)
                .setContentTitle(title).setContentText(text)
                .setContentIntent(ContentIntentUtils.create(context, MainActivity.PAGE_ALARMS, id))
                .addAction(R.drawable.ic_dismiss_alarm_24dp, context.getString(R.string.dismiss_now), piDismiss)
                .build();
        nm.notify(TAG, (int) id, note);
    } else if (ACTION_CANCEL_NOTIFICATION.equals(intent.getAction())) {
        nm.cancel(TAG, (int) id);
    } else if (ACTION_DISMISS_NOW.equals(intent.getAction())) {
        new AlarmController(context, null).cancelAlarm(alarm, false, true);
    }
}

From source file:org.jitsi.android.gui.call.notification.CallNotificationManager.java

/**
 * Binds pending intents to all control <tt>Views</tt>.
 * @param ctx Android context./* w ww. j a v a  2s .  c o m*/
 * @param contentView notification root <tt>View</tt>.
 * @param callID the call ID that will be used in the <tt>Intents</tt>
 */
private void setIntents(Context ctx, RemoteViews contentView, String callID) {
    // Hangup button
    PendingIntent pHangup = PendingIntent.getBroadcast(ctx, 0, CallControl.getHangupIntent(callID),
            PendingIntent.FLAG_CANCEL_CURRENT);
    contentView.setOnClickPendingIntent(R.id.hangup_button, pHangup);

    // Speakerphone button
    PendingIntent pSpeaker = PendingIntent.getBroadcast(ctx, 1, CallControl.getToggleSpeakerIntent(callID),
            PendingIntent.FLAG_CANCEL_CURRENT);
    contentView.setOnClickPendingIntent(R.id.speakerphone, pSpeaker);

    // Mute button
    PendingIntent pMute = PendingIntent.getBroadcast(ctx, 2, CallControl.getToggleMuteIntent(callID),
            PendingIntent.FLAG_CANCEL_CURRENT);
    contentView.setOnClickPendingIntent(R.id.mute_button, pMute);

    // Hold button
    PendingIntent pHold = PendingIntent.getBroadcast(ctx, 3, CallControl.getToggleOnHoldIntent(callID),
            PendingIntent.FLAG_CANCEL_CURRENT);
    contentView.setOnClickPendingIntent(R.id.hold_button, pHold);

    // Show video call Activity
    Intent videoCall = new Intent(ctx, VideoCallActivity.class);
    videoCall.putExtra(CallManager.CALL_IDENTIFIER, callID);
    PendingIntent pVideo = PendingIntent.getActivity(ctx, 4, videoCall, PendingIntent.FLAG_CANCEL_CURRENT);
    contentView.setOnClickPendingIntent(R.id.back_to_call, pVideo);

    // Binds show video call intent to the whole area
    contentView.setOnClickPendingIntent(R.id.notificationContent, pVideo);
}

From source file:com.finchuk.clock2.alarms.background.UpcomingAlarmReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final byte[] alarmBytes = intent.getByteArrayExtra(EXTRA_ALARM);
    // Unmarshall the bytes into a parcel and create our Alarm with it.
    final Alarm alarm = ParcelableUtil.unmarshall(alarmBytes, Alarm.CREATOR);
    if (alarm == null) {
        throw new IllegalStateException("No alarm received");
    }/*from  w  w w  .j a  va2 s  . co m*/

    final long id = alarm.getId();
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    final boolean actionShowSnoozing = ACTION_SHOW_SNOOZING.equals(intent.getAction());
    if (intent.getAction() == null || actionShowSnoozing) {
        // Prepare notification
        // http://stackoverflow.com/a/15803726/5055032
        // Notifications aren't updated on the UI thread, so we could have
        // done this in the background. However, no lengthy operations are
        // done here, so doing so is a premature optimization.
        String title;
        String text;
        if (actionShowSnoozing) {
            if (!alarm.isSnoozed()) {
                throw new IllegalStateException("Can't show snoozing notif. if alarm not snoozed!");
            }
            title = alarm.label().isEmpty() ? context.getString(R.string.alarm) : alarm.label();
            text = context.getString(R.string.title_snoozing_until,
                    TimeFormatUtils.formatTime(context, alarm.snoozingUntil()));
        } else {
            // No intent action required for default behavior
            title = context.getString(R.string.upcoming_alarm);
            text = TimeFormatUtils.formatTime(context, alarm.ringsAt());
            if (!alarm.label().isEmpty()) {
                text = alarm.label() + ", " + text;
            }
        }

        Intent dismissIntent = new Intent(context, UpcomingAlarmReceiver.class).setAction(ACTION_DISMISS_NOW)
                .putExtra(EXTRA_ALARM, ParcelableUtil.marshall(alarm));
        PendingIntent piDismiss = PendingIntent.getBroadcast(context, (int) id, dismissIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        Notification note = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_alarm_24dp)
                .setContentTitle(title).setContentText(text)
                .setContentIntent(ContentIntentUtils.create(context, MainActivity.PAGE_ALARMS, id))
                .addAction(R.drawable.ic_dismiss_alarm_24dp, context.getString(R.string.dismiss_now), piDismiss)
                .build();
        nm.notify(TAG, (int) id, note);
    } else if (ACTION_CANCEL_NOTIFICATION.equals(intent.getAction())) {
        nm.cancel(TAG, (int) id);
    } else if (ACTION_DISMISS_NOW.equals(intent.getAction())) {
        new AlarmController(context, null).cancelAlarm(alarm, false, true);
    }
}

From source file:com.rozrost.www.smartlocationreminder.GeofenceTransitionsIntentService.java

private void AlarmService(String PrimaryKey) {
    Intent intent = new Intent("com.rozrost.www.alertscreen.Receiver");
    intent.putExtra("PrimaryKey", PrimaryKey);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, 0, pendingIntent);
}

From source file:com.swisscom.safeconnect.utils.gcm.GcmBroadcastReceiver.java

private void sendNotification(String title, String msg, Context ctx) {
    mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancelAll();// w w  w.  j av a2  s. co m

    Intent intentSubscriptions = new Intent(ctx, DashboardActivity.class);
    intentSubscriptions.putExtra(DashboardActivity.KEY_OPEN_SUBSCRIPTIONS, true);

    // without FLAG_CANCEL_CURRENT the parameters don't arrive
    PendingIntent subscriptionsIntent = PendingIntent.getActivity(ctx, 0, intentSubscriptions,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
            //.setDefaults(Notification.DEFAULT_ALL) // with DEFAULT_ALL it requires VIBRATE permissions! (on HTC One S 4.1.1)
            .setSmallIcon(R.drawable.ic_notif).setContentTitle(title)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg)
            .addAction(R.drawable.ic_subscription_shoppingcart, ctx.getString(R.string.push_extend),
                    subscriptionsIntent);

    mBuilder.setContentIntent(subscriptionsIntent);
    mBuilder.setAutoCancel(true);

    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}