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:org.ohmage.reminders.notif.Notifier.java

private static void displayNotification(Context context, ArrayList<String> surveys, boolean quiet) {

    // If the notification is to be refreshed quietly, and if it is hidden, do nothing.
    if (quiet && !getNotifVisibility(context)) {
        return;//from  w ww.j  a  v a2  s  .c  o m
    }

    // Cancel any alarms to reshow the notification because we are showing it now
    cancelAlarm(context, ACTION_NOTIF_RESHOW);

    NotificationManager notifMan = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    //Watch for notification cleared events
    Intent deleteIntent = new Intent(context, NotifReceiver.class).setAction(ACTION_NOTIF_DELETED);
    PendingIntent piDelete = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    //Watch for notification clicked events
    Intent intent = new Intent(context, NotifReceiver.class).setAction(ACTION_NOTIF_CLICKED)
            .putExtra(EXTRA_SURVEYS, new ArrayList<String>(surveys));
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Constructs the Builder object.
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.survey_notification)
            .setContentText(context.getResources().getQuantityString(R.plurals.survey_notification_message,
                    surveys.size()))
            .setAutoCancel(true)
            .setContentTitle(context.getString(R.string.notifications_multi_title, surveys.size()))
            .setContentIntent(pi).setDeleteIntent(piDelete);

    if (!quiet) {
        builder.setDefaults(Notification.DEFAULT_ALL);
    }

    if (surveys.size() == 1) {
        Intent ignoreIntent = new Intent(context, NotifReceiver.class).setAction(ACTION_NOTIF_IGNORED)
                .putExtra(EXTRA_SURVEYS, surveys);
        PendingIntent piIgnore = PendingIntent.getBroadcast(context, 0, ignoreIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        Intent snoozeIntent = new Intent(context, NotifReceiver.class).setAction(ACTION_NOTIF_SNOOZED);
        PendingIntent piSnooze = PendingIntent.getBroadcast(context, 0, snoozeIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        builder.addAction(R.drawable.stat_notify_alarm, context.getString(R.string.snooze), piSnooze).addAction(
                android.R.drawable.ic_menu_close_clear_cancel, context.getString(R.string.ignore), piIgnore);

        // Get the survey name
        Cursor cursor = context.getContentResolver().query(Reminders.buildRemindersUri(),
                new String[] { Reminders.REMINDER_NAME }, Reminders._ID + "=?", new String[] { surveys.get(0) },
                null);
        if (cursor.moveToFirst()) {
            builder.setContentTitle(cursor.getString(0));
        }
    }
    notifMan.notify(NOIF_ID, builder.build());

    //Save the current visibility
    saveNotifVisibility(context, true);
}

From source file:com.androzic.navigation.NavigationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        Intent activity = new Intent(this, MainActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        String action = intent.getAction();
        if (action == null)
            return 0;
        Bundle extras = intent.getExtras();
        if (action.equals(NAVIGATE_MAPOBJECT)) {
            MapObject mo = new MapObject();
            mo.name = extras.getString(EXTRA_NAME);
            mo.latitude = extras.getDouble(EXTRA_LATITUDE);
            mo.longitude = extras.getDouble(EXTRA_LONGITUDE);
            mo.proximity = extras.getInt(EXTRA_PROXIMITY);
            activity.putExtra(MainActivity.LAUNCH_ACTIVITY, HSIActivity.class);
            contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, activity,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            navigateTo(mo);//from www.j a v  a  2  s. c  o m
        }
        if (action.equals(NAVIGATE_MAPOBJECT_WITH_ID)) {
            long id = extras.getLong(EXTRA_ID);
            MapObject mo = application.getMapObject(id);
            if (mo == null)
                return 0;
            activity.putExtra(MainActivity.LAUNCH_ACTIVITY, HSIActivity.class);
            contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, activity,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            navigateTo(mo);
        }
        if (action.equals(NAVIGATE_ROUTE)) {
            int index = extras.getInt(EXTRA_ROUTE_INDEX);
            int dir = extras.getInt(EXTRA_ROUTE_DIRECTION, DIRECTION_FORWARD);
            int start = extras.getInt(EXTRA_ROUTE_START, -1);
            activity.putExtra(MainActivity.SHOW_FRAGMENT, RouteDetails.class);
            activity.putExtra("index", index);
            contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, activity,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            Route route = application.getRoute(index);
            if (route == null)
                return 0;
            navigateTo(route, dir);
            if (start != -1)
                setRouteWaypoint(start);
        }
    }
    return START_STICKY;
}

From source file:com.tenforwardconsulting.cordova.bgloc.AbstractLocationService.java

/**
 * Adds an onclick handler to the notification
 *///from ww w .  j  a  v  a2s.c o m
protected NotificationCompat.Builder setClickEvent(NotificationCompat.Builder builder) {
    int requestCode = new Random().nextInt();
    Context context = getApplicationContext();
    String packageName = context.getPackageName();
    Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(context, requestCode, launchIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    return builder.setContentIntent(contentIntent);
}

From source file:com.sspai.dkjt.service.GenerateFrameService.java

@Override
public void doneImage(final Uri imageUri) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        @Override//  w ww  . j  a  v  a 2s . com
        public void run() {
            bus.post(new Events.SingleImageProcessed(device, imageUri));
        }
    });

    // Create the intent to let the user share the image
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
    Intent chooserIntent = Intent.createChooser(sharingIntent, null);
    chooserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationBuilder.addAction(R.drawable.ic_action_share, getResources().getString(R.string.share),
            PendingIntent.getActivity(this, 0, chooserIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to let the user rate the app
    Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(ConfigString.MARKET_URL));
    notificationBuilder.addAction(R.drawable.ic_action_rate, getResources().getString(R.string.rate),
            PendingIntent.getActivity(this, 0, rateIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    // Create the intent to show the screenshot in gallery
    Intent launchIntent = new Intent(Intent.ACTION_VIEW);
    launchIntent.setDataAndType(imageUri, "image/png");
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    notificationBuilder.setContentTitle(resources.getString(R.string.screenshot_saved_title))
            .setContentText(resources.getString(R.string.single_screenshot_saved, device.name()))
            .setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, 0))
            .setWhen(System.currentTimeMillis()).setProgress(0, 0, false).setAutoCancel(true);

    notificationManager.notify(DFG_NOTIFICATION_ID, notificationBuilder.build());
}

From source file:com.nextgis.ngm_clink_monitoring.adapters.FoclSyncAdapter.java

public static void sendNotification(Context context, int notificationType, String errorMsg) {
    Intent notificationIntent = new Intent(context, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
            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. ja va 2s . com

    switch (notificationType) {
    case FoclSyncAdapter.IS_STARTED:
        builder.setProgress(0, 0, true).setSmallIcon(R.drawable.ic_sync_started)
                .setTicker(context.getString(R.string.sync_started))
                .setContentTitle(context.getString(R.string.synchronization))
                .setContentText(context.getString(R.string.sync_progress));
        break;

    case FoclSyncAdapter.IS_FINISHED:
        builder.setProgress(0, 0, false).setSmallIcon(R.drawable.ic_sync_finished)
                .setTicker(context.getString(R.string.sync_finished))
                .setContentTitle(context.getString(R.string.synchronization))
                .setContentText(context.getString(R.string.sync_finished));
        break;

    case FoclSyncAdapter.IS_CANCELED:
        builder.setProgress(0, 0, false).setSmallIcon(R.drawable.ic_sync_error)
                .setTicker(context.getString(R.string.sync_canceled))
                .setContentTitle(context.getString(R.string.synchronization))
                .setContentText(context.getString(R.string.sync_canceled));
        break;

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

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

From source file:net.kseek.camtest.ui.CamtestActivity.java

public void onStart() {
    super.onStart();

    // Lock screen
    mWakeLock.acquire();/*  w w w .  j  ava  2s.co m*/

    // Did the user disabled the notification ?
    if (mApplication.notificationEnabled) {
        Intent notificationIntent = new Intent(this, CamtestActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        Notification notification = builder.setContentIntent(pendingIntent).setWhen(System.currentTimeMillis())
                .setTicker(getText(R.string.notification_title)).setSmallIcon(R.drawable.icon)
                .setContentTitle(getText(R.string.notification_title))
                .setContentText(getText(R.string.notification_content)).build();
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);
    } else {
        removeNotification();
    }

    bindService(new Intent(this, CustomHttpServer.class), mHttpServiceConnection, Context.BIND_AUTO_CREATE);
    bindService(new Intent(this, CustomRtspServer.class), mRtspServiceConnection, Context.BIND_AUTO_CREATE);

}

From source file:org.digitalcampus.oppia.service.DownloadService.java

private void notifyDownloads(String action, String fileUrl) {
    //If there are no more pending downloads after the completion of this one, send a Notification
    if (action.equals(ACTION_COMPLETE) && (tasksDownloading == null || tasksDownloading.size() == 0)) {
        Log.d(TAG, "Sending notification from Service for the completion of all pending media downloads");

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(),
                PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder mBuilder = OppiaNotificationUtils.getBaseBuilder(this, true);
        mBuilder.setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_media_subject)).setContentIntent(contentIntent)
                .build();//from  w w w .  j  a v  a2 s .  co m

        OppiaNotificationUtils.sendNotification(this, 0, mBuilder.build());
    }

}

From source file:com.github.shareme.gwscleanstatusbar.CleanStatusBarService.java

private void showNotification() {
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setPriority(NotificationCompat.PRIORITY_MIN).setOngoing(true).setWhen(0)
            .setContentTitle(getString(R.string.clean_status_bar_is_running))
            .setContentText(getString(R.string.touch_to_configure)).setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(PendingIntent.getActivity(getApplicationContext(), 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT));
    startForeground(NOTIFICATION_ID, builder.build());
}

From source file:org.apps8os.motivator.services.NotificationService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (prefs.getBoolean(SettingsActivity.KEY_SEND_NOTIFICATIONS, true)) {
        // Set up the notification with a builder
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Bundle extras = intent.getExtras();

        // Check the notification type.
        int notificationType = extras.getInt(NOTIFICATION_TYPE);
        if (notificationType == NOTIFICATION_MOOD) {
            // Cancel all previous notifications.
            manager.cancelAll();//from   ww  w  .  ja v a  2 s . c o  m

            SprintDataHandler dataHandler = new SprintDataHandler(this);
            Sprint currentSprint = dataHandler.getCurrentSprint();
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            // If there is no current sprint, cancel alarms.
            if (currentSprint == null) {
                Sprint latestEndedSprint = dataHandler.getLatestEndedSprint();
                if (latestEndedSprint != null) {
                    if (latestEndedSprint.endedYesterday()) {
                        builder.setContentTitle(getString(R.string.completed_sprint));
                        builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
                        builder.setAutoCancel(true);
                        Intent resultIntent = new Intent(this, MainActivity.class);
                        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                        stackBuilder.addParentStack(MainActivity.class);
                        stackBuilder.addNextIntent(resultIntent);
                        PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                                PendingIntent.FLAG_CANCEL_CURRENT);
                        builder.setContentIntent(pendingResultIntent);
                        manager.notify(NOTIFICATION_ID_SPRINT_ENDED, builder.build());
                    }
                }
                Intent notificationIntent = new Intent(this, NotificationService.class);
                PendingIntent pendingNotificationIntent = PendingIntent.getService(this, 0, notificationIntent,
                        PendingIntent.FLAG_CANCEL_CURRENT);
                alarmManager.cancel(pendingNotificationIntent);
            } else {
                builder.setContentTitle(getString(R.string.today_screen_mood));
                int currentDateInSprint = currentSprint.getCurrentDayOfTheSprint();

                builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
                // Remove the notification when the user clicks it.
                builder.setAutoCancel(true);

                // Where to go when user clicks the notification
                Intent resultIntent = new Intent(this, MoodQuestionActivity.class);
                DayDataHandler moodDataHandler = new DayDataHandler(this);

                // Check if there were events yesterday.
                DayInHistory yesterday = moodDataHandler.getDayInHistory(
                        System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
                yesterday.setEvents();
                ArrayList<MotivatorEvent> yesterdayEvents = yesterday.getUncheckedEvents(this);
                if (!yesterdayEvents.isEmpty()) {
                    // Put the events as extras to the intent so that we can pass them to the checking activity.
                    resultIntent.putExtra(MotivatorEvent.YESTERDAYS_EVENTS, yesterdayEvents);
                    resultIntent.putExtra(EventDataHandler.EVENTS_TO_CHECK, true);
                    builder.setContentText(getString(R.string.you_had_an_event_yesterday));
                } else {
                    // No events to check.
                    resultIntent.putExtra(EventDataHandler.EVENTS_TO_CHECK, false);
                    EventDataHandler eventHandler = new EventDataHandler(this);
                    long lastAddedEventTimestamp = eventHandler.getLatestAddedEventTimestamp();
                    if (lastAddedEventTimestamp != 0L && System.currentTimeMillis()
                            - lastAddedEventTimestamp > TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS)) {
                        builder.setContentText(getString(R.string.plan_reminder));
                    } else {
                        builder.setContentText(getString(R.string.today_is_the_day) + " " + currentDateInSprint
                                + "/" + currentSprint.getDaysInSprint() + " - "
                                + currentSprint.getSprintTitle());
                    }
                }
                // Preserve the normal navigation of the app by adding the parent stack of the result activity
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                stackBuilder.addParentStack(MoodQuestionActivity.class);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_CANCEL_CURRENT);
                builder.setContentIntent(pendingResultIntent);
                manager.notify(NOTIFICATION_ID_MOOD, builder.build());
            }
        }

        else if (notificationType == NOTIFICATION_EVENT_START) {
            // Set up a notification for the start of an event.
            int eventId = extras.getInt(EventDataHandler.EVENT_ID);
            String eventName = extras.getString(EventDataHandler.EVENT_NAME);
            builder.setContentTitle(getString(R.string.you_have_an_event_starting));
            builder.setContentText(eventName);
            builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
            // Remove the notification when the user clicks it.
            builder.setAutoCancel(true);

            Intent resultIntent = new Intent(this, EventDetailsActivity.class);
            resultIntent.putExtra(EventDataHandler.EVENT_ID, eventId);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(EventDetailsActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingResultIntent);

            manager.notify(eventId, builder.build());
        }

        else if (notificationType == NOTIFICATION_EVENT_END) {
            // Set up a notification for the start of an event.
            int eventId = extras.getInt(EventDataHandler.EVENT_ID);
            builder.setContentTitle(getString(R.string.event_ending));
            builder.setContentText(getString(R.string.go_home));
            builder.setSmallIcon(R.drawable.ic_stat_notification_icon_1);
            // Remove the notification when the user clicks it.
            builder.setAutoCancel(true);

            Intent resultIntent = new Intent(this, EventDetailsActivity.class);
            resultIntent.putExtra(EventDataHandler.EVENT_ID, eventId);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
            stackBuilder.addParentStack(EventDetailsActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent pendingResultIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingResultIntent);

            manager.notify(eventId + 10000, builder.build());
        }
    }
}

From source file:au.com.smarttrace.beacons.BluetoothService.java

private void connect() {
    btScanner = btAdapter.getBluetoothLeScanner();
    if (btScanner != null && btAdapter.isEnabled()) {

        Log.d(TAG, "START SCANNING!");
        btScanner.startScan(btFilters, btSettings, scanCallback);
        scanning = true;/*  w w w  . j av  a  2s . c o m*/
        sendChange(true);

        //XXX: workaround to avoid bluetooth scan halt
        AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(BluetoothService.ACTION_RESCAN, null, this, BluetoothService.class);
        alarm.setExact(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 15000l,
                PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));

        //         future = executor.schedule(this, DELAY_REPEAT_SCAN, TimeUnit.SECONDS);
    }
}