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.sean.takeastand.storage.ScheduleEditor.java

private void cancelDailyRepeatingAlarm(int UID) {
    Intent intent = new Intent(mContext, StartScheduleReceiver.class);
    intent.putExtra(Constants.ALARM_UID, UID);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, UID, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);/*w w  w  .  jav a  2  s.c o m*/
    Log.i(TAG, "Canceled a daily repeating alarm");
}

From source file:com.jefftharris.passwdsafe.NotificationMgr.java

/** Load the expiration entries from the database */
private void loadEntries(SQLiteDatabase db) throws SQLException {
    long expiration;
    if (itsExpiryFilter != null) {
        expiration = itsExpiryFilter.getExpiryFromNow(null);
    } else {//www. j  av a  2 s.  c  o  m
        expiration = Long.MIN_VALUE;
    }
    LongReference nextExpiration = new LongReference(Long.MAX_VALUE);

    itsNotifUris.clear();
    HashSet<Long> uris = new HashSet<>();
    ArrayList<Long> removeUriIds = new ArrayList<>();
    Cursor uriCursor = db.query(DB_TABLE_URIS, new String[] { DB_COL_URIS_ID, DB_COL_URIS_URI }, null, null,
            null, null, null);
    try {
        while (uriCursor.moveToNext()) {
            long id = uriCursor.getLong(0);
            Uri uri = Uri.parse(uriCursor.getString(1));
            boolean exists = loadUri(id, uri, uris, expiration, nextExpiration, db);
            if (!exists) {
                removeUriIds.add(id);
            }
        }
    } finally {
        uriCursor.close();
    }

    Iterator<HashMap.Entry<Long, UriNotifInfo>> iter = itsUriNotifs.entrySet().iterator();
    while (iter.hasNext()) {
        HashMap.Entry<Long, UriNotifInfo> entry = iter.next();
        if (!uris.contains(entry.getKey())) {
            itsNotifyMgr.cancel(entry.getValue().getNotifId());
            iter.remove();
        }
    }

    for (Long removeId : removeUriIds) {
        removeUri(removeId, db);
    }

    PasswdSafeUtil.dbginfo(TAG, "nextExpiration: %tc", nextExpiration.itsValue);

    if ((nextExpiration.itsValue != Long.MAX_VALUE) && (itsExpiryFilter != null)) {
        if (itsTimerIntent == null) {
            Intent intent = new Intent(PasswdSafeApp.EXPIRATION_TIMEOUT_INTENT);
            itsTimerIntent = PendingIntent.getBroadcast(itsCtx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        }
        long nextTimer = System.currentTimeMillis() + (nextExpiration.itsValue - expiration);
        PasswdSafeUtil.dbginfo(TAG, "nextTimer: %tc", nextTimer);
        itsAlarmMgr.set(AlarmManager.RTC, nextTimer, itsTimerIntent);
    } else if (itsTimerIntent != null) {
        PasswdSafeUtil.dbginfo(TAG, "cancel expiration timer");
        itsAlarmMgr.cancel(itsTimerIntent);
    }
}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Restart the current app. Supply the class to start on startup
 *///from  ww w .j a  v  a  2s . c  om
public void restartApp(Class classToStart) {
    Intent inte = new Intent(_context, classToStart);
    PendingIntent inteP = PendingIntent.getActivity(_context, 555, inte, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) _context.getSystemService(Context.ALARM_SERVICE);
    if (_context instanceof Activity) {
        ((Activity) _context).finish();
    }
    if (mgr != null) {
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, inteP);
    } else {
        inte.addFlags(FLAG_ACTIVITY_NEW_TASK);
        _context.startActivity(inte);
    }
    Runtime.getRuntime().exit(0);
}

From source file:com.nextgis.ngm_clink_monitoring.services.FoclReportService.java

protected static Notification getNotification(Context context, int notificationType, String errorMsg) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

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

    builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
            .setContentIntent(contentIntent).setWhen(System.currentTimeMillis()).setAutoCancel(true)
            .setOngoing(false);//from  ww w . j  ava2s  . c  o  m

    switch (notificationType) {
    case NOTIFICATION_START:
        builder.setProgress(0, 0, true).setSmallIcon(R.drawable.ic_sync_started)
                .setTicker(context.getString(R.string.report_started))
                .setContentTitle(context.getString(R.string.report))
                .setContentText(context.getString(R.string.report_progress));
        break;

    case NOTIFICATION_FINISH:
        builder.setProgress(0, 0, false).setSmallIcon(R.drawable.ic_sync_finished)
                .setTicker(context.getString(R.string.report_finished))
                .setContentTitle(context.getString(R.string.report))
                .setContentText(context.getString(R.string.report_finished));
        break;

    case NOTIFICATION_CANCELED:
        builder.setProgress(0, 0, false).setSmallIcon(R.drawable.ic_sync_error)
                .setTicker(context.getString(R.string.report_canceled))
                .setContentTitle(context.getString(R.string.report))
                .setContentText(context.getString(R.string.report_canceled));
        break;

    case NOTIFICATION_ERROR:
        builder.setProgress(0, 0, false).setSmallIcon(R.drawable.ic_sync_error)
                .setTicker(context.getString(R.string.report_error))
                .setContentTitle(context.getString(R.string.report_error)).setContentText(errorMsg);
        break;
    }

    return builder.build();
}

From source file:com.darshancomputing.alockblock.ALockBlockService.java

private void minimize() {
    mNotificationManager.cancelAll();/*from  ww  w  . j a  v  a2s  . co  m*/
    stopForeground(true);

    if (!settings.getBoolean(SettingsActivity.KEY_ALWAYS_SHOW_NOTIFICATION, false))
        return;

    Intent mainWindowIntent = new Intent(context, ALockBlockActivity.class);
    mainWindowPendingIntent = PendingIntent.getActivity(context, 0, mainWindowIntent, 0);

    ComponentName comp = new ComponentName(getPackageName(), ALockBlockService.class.getName());
    Intent disableIntent = new Intent().setComponent(comp).putExtra(EXTRA_ACTION, ACTION_DISABLE);
    PendingIntent disablePendingIntent = PendingIntent.getService(this, 0, disableIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder kgunb = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.kg_unlocked)
            .setLargeIcon(largeIconL).setContentTitle("Lock Screen Enabled").setContentText("A Lock Block")
            .setContentIntent(mainWindowPendingIntent).setShowWhen(false).setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MIN);

    if (settings.getBoolean(SettingsActivity.KEY_REENABLE_FROM_NOTIFICATION, false))
        kgunb.addAction(R.drawable.ic_menu_login, "Disable", disablePendingIntent);

    mNotificationManager.notify(NOTIFICATION_KG_UNLOCKED, kgunb.build());
}

From source file:com.dogar.geodesic.map.MainActivity.java

private void restartApp() {
    Intent mStartActivity = new Intent(this, MainActivity.class);
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId, mStartActivity,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);//  w w w . ja v  a  2  s  .  c o m
}

From source file:graaby.app.wallet.services.GcmIntentService.java

private void sendNotification(final String msg) {
    try {/*from w  ww  . j a v a 2s .  c  om*/
        JSONObject object = new JSONObject(msg);
        PendingIntent pendingIntent = null;
        String notificationTitle, smallContentText, smallContentInfo = "";
        int notificationImageResource = R.drawable.ic_noty_point, notificationID,
                uniquePendingId = (int) (System.currentTimeMillis() & 0xfffffff);

        SharedPreferences pref = getSharedPreferences("pref_notification", Activity.MODE_PRIVATE);

        Uri noty_sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        if (!TextUtils.isEmpty(pref.getString("notifications_new_message_ringtone", ""))) {
            noty_sound = Uri.parse(pref.getString("notifications_new_message_ringtone", ""));
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSound(noty_sound)
                .setLights(0xff2ECC71, 300, 1000).setAutoCancel(Boolean.TRUE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            mBuilder.setCategory(Notification.CATEGORY_SOCIAL);

        if (pref.getBoolean("notifications_new_message_vibrate", true)) {
            mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
        }

        Intent activityIntent = new Intent();
        switch (NotificationType.getType(object.getInt(getString(R.string.field_gcm_msg_type)))) {
        case SHARE_POINTS:
            //user received points from contact
            String sender = object.getString(getString(R.string.field_gcm_name));
            int amount = object.getInt(getString(R.string.contact_send_amount));
            notificationTitle = getString(R.string.gcm_message_recieved_points);
            smallContentText = String.format(getString(R.string.gcm_message_recieved_points_content), sender,
                    amount);
            smallContentInfo = String.valueOf(amount);
            notificationImageResource = R.drawable.ic_noty_point;
            notificationID = getRandomInt(0, 50);

            mBuilder.setColor(getResources().getColor(R.color.alizarin));

            activityIntent.setClass(this, PointReceivedActivity.class);
            activityIntent.setAction(NOTIFICATION_ACTION_POINTS);
            activityIntent.putExtra(Helper.INTENT_CONTAINER_INFO, msg);

            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(PointReceivedActivity.class);
            stackBuilder.addNextIntent(activityIntent);

            Intent broadcastIntent = new Intent(this, GraabyBroadcastReceiver.class);
            broadcastIntent.setAction(GraabyBroadcastReceiver.ACTION_THANK);
            broadcastIntent.putExtra(Helper.INTENT_CONTAINER_INFO, msg);
            broadcastIntent.putExtra(Helper.NOTIFICATIONID, notificationID);

            PendingIntent pendingBroadcastIntent = PendingIntent.getBroadcast(this, uniquePendingId,
                    broadcastIntent, 0);

            mBuilder.addAction(R.drawable.ic_action_accept, "Say thanks", pendingBroadcastIntent);

            pendingIntent = stackBuilder.getPendingIntent(uniquePendingId, PendingIntent.FLAG_ONE_SHOT);
            break;
        case TRANSACTION:
            //user made a transaction
            amount = object.getInt(getString(R.string.contact_send_amount));
            String outlet = object.getString(getString(R.string.field_business_name));
            notificationTitle = getString(R.string.gcm_message_transaction);
            smallContentText = String.format(getString(R.string.gcm_message_transaction_content), amount,
                    outlet);
            smallContentInfo = String.valueOf(amount);
            notificationImageResource = R.drawable.ic_noty_point;
            notificationID = getRandomInt(51, 100);

            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(smallContentText));
            mBuilder.setColor(getResources().getColor(R.color.alizarin));

            activityIntent.setClass(this, PointReceivedActivity.class);
            activityIntent.setAction(NOTIFICATION_ACTION_TX);
            activityIntent.putExtra(Helper.INTENT_CONTAINER_INFO, msg);
            activityIntent.putExtra(Helper.NOTIFICATIONID, notificationID);

            pendingIntent = PendingIntent.getActivity(this, 0, activityIntent, PendingIntent.FLAG_ONE_SHOT);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                mBuilder.setCategory(Notification.CATEGORY_STATUS);
            break;
        case NEW_VOUCHER:
            //new marketplace voucher has appeared
            outlet = object.getString(getString(R.string.field_business_name));
            notificationTitle = getString(R.string.gcm_message_market);
            if (object.has("msg"))
                smallContentText = object.getString("msg") + " @ " + outlet;
            else
                smallContentText = String.format(getString(R.string.gcm_message_market_content), outlet);
            smallContentInfo = "";
            notificationImageResource = R.drawable.ic_gcm_discount;
            notificationID = NOTIFICATION_ID_NEW_MARKET;

            mBuilder.setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(String.format(getString(R.string.gcm_message_market_content), outlet)));
            mBuilder.setColor(getResources().getColor(R.color.sunflower));

            activityIntent.setClass(this, MarketActivity.class);
            activityIntent.setAction(NOTIFICATION_ACTION_NEW_DISCOUNT);
            activityIntent.putExtra(Helper.INTENT_CONTAINER_INFO, msg);
            activityIntent.putExtra(Helper.NOTIFICATIONID, NOTIFICATION_ID_NEW_MARKET);
            activityIntent.putExtra(Helper.MY_DISCOUNT_ITEMS_FLAG, false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                mBuilder.setCategory(Notification.CATEGORY_PROMO);
            break;
        case NEW_FEED:
            notificationTitle = "New message";
            smallContentText = object.getString("msg");
            notificationImageResource = R.drawable.ic_noty_announcement;
            notificationID = NOTIFICATION_ID_FEED;

            activityIntent.setClass(this, FeedActivity.class);
            activityIntent.putExtra(Helper.NOTIFICATIONID, NOTIFICATION_ID_FEED);
            activityIntent.setAction(NOTIFICATION_ACTION_FEED);

            mBuilder.setColor(getResources().getColor(R.color.alizarin));

            pendingIntent = TaskStackBuilder.create(this).addNextIntentWithParentStack(activityIntent)
                    .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            break;
        case THANK_CONTACT:
            //contact thanks you for sending points
            String thanksString = object.getString(getString(R.string.field_gcm_name));
            notificationTitle = getString(R.string.gcm_message_thanked);
            smallContentText = String.format(getString(R.string.gcm_message_thanked_small_content),
                    thanksString);
            mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(smallContentText));
            notificationImageResource = R.drawable.ic_noty_thank;
            notificationID = NOTIFICATION_ID_THANKED;
            mBuilder.setColor(getResources().getColor(R.color.belizehole));

            break;
        case CHECKIN:
            //checkin notification
            outlet = object.getString(getString(R.string.field_gcm_name));
            notificationTitle = getString(R.string.gcm_message_checkin_title);
            smallContentText = String.format(getString(R.string.gcm_message_checkin_small_content), outlet);
            notificationImageResource = R.drawable.ic_gcm_checkin;
            notificationID = NOTIFICATION_ID_CHECKIN;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                mBuilder.setCategory(Notification.CATEGORY_STATUS);
            mBuilder.setColor(getResources().getColor(R.color.wisteria));

            break;
        case INFO_NEEDED:
            notificationTitle = getString(R.string.gcm_message_meta_info_title);
            smallContentText = getString(R.string.gcm_message_meta_info_title);
            notificationImageResource = R.drawable.ic_noty_information;
            notificationID = NOTIFICATION_ID_INFO;

            mBuilder.setColor(getResources().getColor(R.color.emarald));

            activityIntent.setClass(this, ExtraInfoActivity.class);
            activityIntent.setAction(NOTIFICATION_ACTION_INFO);
            activityIntent.putExtra(Helper.INTENT_CONTAINER_INFO, msg);
            activityIntent.putExtra(Helper.NOTIFICATIONID, notificationID);

            pendingIntent = PendingIntent.getActivity(this, 0, activityIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            break;
        case NONE:
        default:
            notificationTitle = "";
            smallContentText = "";
            smallContentInfo = "";
            notificationID = 0;
        }

        if (pendingIntent == null)
            pendingIntent = PendingIntent.getActivity(this, 0, activityIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationManager mNotificationManager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);

        mBuilder.setLargeIcon(BitmapFactory.decodeResource(getResources(), notificationImageResource))
                .setSmallIcon(R.drawable.ic_noty_graaby).setContentTitle(notificationTitle)
                .setContentText(smallContentText).setContentInfo(smallContentInfo)
                .setContentIntent(pendingIntent);

        mNotificationManager.notify(notificationID, mBuilder.build());
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:eu.faircode.netguard.SinkholeService.java

private Notification getForegroundNotification() {
    Intent main = new Intent(this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_security_white_24dp).setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.msg_started)).setContentIntent(pi)
            .setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET)
            .setColor(ContextCompat.getColor(this, R.color.colorPrimary)).setAutoCancel(true);

    return notification.build();
}

From source file:com.twofours.surespot.services.SurespotGcmListenerService.java

private void generateSystemNotification(Context context, String title, String message, String tag, int id) {

    // need to use same builder for only alert once to work:
    // http://stackoverflow.com/questions/6406730/updating-an-ongoing-notification-quietly
    mBuilder.setAutoCancel(true).setOnlyAlertOnce(true);

    int defaults = 0;

    mBuilder.setLights(0xff0000FF, 500, 5000);
    defaults |= Notification.DEFAULT_SOUND;
    defaults |= Notification.DEFAULT_VIBRATE;

    mBuilder.setDefaults(defaults);/*from  w w  w.java2s. c  o m*/

    PendingIntent contentIntent = PendingIntent.getActivity(context, (int) new Date().getTime(), new Intent(),
            PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification = UIUtils.generateNotification(mBuilder, contentIntent, getPackageName(), title,
            message);

    mNotificationManager.notify(tag, id, notification);
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Sets alert in AlarmManger and StatusBar.  This is what will
 * actually launch the alert when the alarm triggers.
 *
 * @param alarm Alarm.//from  w ww  .  ja va  2  s.c om
 * @param atTimeInMillis milliseconds since epoch
 */
private static void enableAlert(Context context, final Alarm alarm, final long atTimeInMillis) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (Log.LOGV) {
        Log.v("** setAlert id " + alarm.id + " atTime " + atTimeInMillis);
    }

    Intent intent = new Intent(ALARM_ALERT_ACTION);

    // XXX: This is a slight hack to avoid an exception in the remote
    // AlarmManagerService process. The AlarmManager adds extra data to
    // this Intent which causes it to inflate. Since the remote process
    // does not know about the Alarm class, it throws a
    // ClassNotFoundException.
    //
    // To avoid this, we marshall the data ourselves and then parcel a plain
    // byte[] array. The AlarmReceiver class knows to build the Alarm
    // object from the byte[] array.
    Parcel out = Parcel.obtain();
    alarm.writeToParcel(out, 0);
    out.setDataPosition(0);
    intent.putExtra(ALARM_RAW_DATA, out.marshall());

    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    am.set(AlarmManager.RTC_WAKEUP, atTimeInMillis, sender);

    setStatusBarIcon(context, true);

    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(atTimeInMillis);
    String timeString = formatDayAndTime(context, c);
    saveNextAlarm(context, timeString);
}