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.chromium.ChromeNotifications.java

private void makeNotification(final CordovaArgs args) throws JSONException {
    String notificationId = args.getString(0);
    JSONObject options = args.getJSONObject(1);
    Resources resources = cordova.getActivity().getResources();
    Bitmap largeIcon = makeBitmap(options.getString("iconUrl"),
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height));
    int smallIconId = resources.getIdentifier("notification_icon", "drawable",
            cordova.getActivity().getPackageName());
    if (smallIconId == 0) {
        smallIconId = resources.getIdentifier("icon", "drawable", cordova.getActivity().getPackageName());
    }//from  w w  w . ja  v  a2  s.  c o  m
    NotificationCompat.Builder builder = new NotificationCompat.Builder(cordova.getActivity())
            .setSmallIcon(smallIconId).setContentTitle(options.getString("title"))
            .setContentText(options.getString("message")).setLargeIcon(largeIcon)
            .setPriority(options.optInt("priority"))
            .setContentIntent(makePendingIntent(NOTIFICATION_CLICKED_ACTION, notificationId, -1,
                    PendingIntent.FLAG_CANCEL_CURRENT))
            .setDeleteIntent(makePendingIntent(NOTIFICATION_CLOSED_ACTION, notificationId, -1,
                    PendingIntent.FLAG_CANCEL_CURRENT));
    double eventTime = options.optDouble("eventTime");
    if (eventTime != 0) {
        builder.setWhen(Math.round(eventTime));
    }
    JSONArray buttons = options.optJSONArray("buttons");
    if (buttons != null) {
        for (int i = 0; i < buttons.length(); i++) {
            JSONObject button = buttons.getJSONObject(i);
            builder.addAction(android.R.drawable.ic_dialog_info, button.getString("title"), makePendingIntent(
                    NOTIFICATION_BUTTON_CLICKED_ACTION, notificationId, i, PendingIntent.FLAG_CANCEL_CURRENT));
        }
    }
    String type = options.getString("type");
    Notification notification;
    if ("image".equals(type)) {
        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(builder);
        String bigImageUrl = options.optString("imageUrl");
        if (!bigImageUrl.isEmpty()) {
            bigPictureStyle.bigPicture(makeBitmap(bigImageUrl, 0, 0));
        }
        notification = bigPictureStyle.build();
    } else if ("list".equals(type)) {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
        JSONArray items = options.optJSONArray("items");
        if (items != null) {
            for (int i = 0; i < items.length(); i++) {
                JSONObject item = items.getJSONObject(i);
                inboxStyle.addLine(Html.fromHtml("<b>" + item.getString("title")
                        + "</b>&nbsp;&nbsp;&nbsp;&nbsp;" + item.getString("message")));
            }
        }
        notification = inboxStyle.build();
    } else {
        if ("progress".equals(type)) {
            int progress = options.optInt("progress");
            builder.setProgress(100, progress, false);
        }
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle(builder);
        bigTextStyle.bigText(options.getString("message"));
        notification = bigTextStyle.build();
    }
    notificationManager.notify(notificationId.hashCode(), notification);
}

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

/**
 * Update notification and vibrate and/or flash a LED light if needed
 *
 * @param text       The ticker text to display
 * @param contentText       The text to display in the notification dropdown
 * @param vibrate True if the device should vibrate, false otherwise
 * @param sound True if the device should make sound, false otherwise
 * @param light True if the device should flash a LED light, false otherwise
 */// w ww.  ja  v  a 2  s  .c o  m
private void updateNotification(String text, String contentText, boolean vibrate, boolean sound,
        boolean light) {
    Intent disconnect = new Intent("disconnect_all");
    PendingIntent pendingIntentDisconnect = PendingIntent.getBroadcast(this, 0, disconnect,
            PendingIntent.FLAG_CANCEL_CURRENT);

    if (foreground) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentText(text);
        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"));
        }

        Intent notifyIntent = new Intent(this, MainActivity.class);
        notifyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);

        if (contentText == null) {
            if (newMentions >= 1) {
                StringBuilder sb = new StringBuilder();
                for (Conversation conv : mentions.values()) {
                    sb.append(conv.getName() + " (" + conv.getNewMentions() + "), ");
                }
                contentText = getString(R.string.notification_mentions, sb.substring(0, sb.length() - 2));
            } else if (!connectedServerTitles.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (String title : connectedServerTitles) {
                    sb.append(title + ", ");
                }
                contentText = getString(R.string.notification_connected, sb.substring(0, sb.length() - 2));
            } else {
                contentText = getString(R.string.notification_not_connected);
            }
        }

        builder.setContentIntent(contentIntent).setWhen(System.currentTimeMillis())
                .setContentTitle(getText(R.string.app_name)).setContentText(contentText);
        Notification notification = builder.build();

        if (vibrate) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }

        if (sound) {
            notification.defaults |= Notification.DEFAULT_SOUND;
        }

        if (light) {
            notification.ledARGB = NOTIFICATION_LED_COLOR;
            notification.ledOnMS = NOTIFICATION_LED_ON_MS;
            notification.ledOffMS = NOTIFICATION_LED_OFF_MS;
            notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        }

        notification.number = newMentions;

        notificationManager.notify(FOREGROUND_NOTIFICATION, notification);
    }
}

From source file:org.dmfs.tasks.notification.NotificationActionUtils.java

/**
 * Creates and displays an Undo notification for the specified {@link NotificationAction}.
 *//*from   www.  jav  a 2s  . c  o  m*/
public static void createUndoNotification(final Context context, NotificationAction action) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContentTitle(context.getString(action.getActionTextResId()

    ));
    builder.setSmallIcon(R.drawable.ic_notification);
    builder.setWhen(action.getWhen());

    // disable sound & vibration
    builder.setDefaults(0);

    final RemoteViews undoView = new RemoteViews(context.getPackageName(), R.layout.undo_notification);
    undoView.setTextViewText(R.id.description_text, context.getString(action.mActionTextResId));

    final String packageName = context.getPackageName();

    final Intent clickIntent = new Intent(context, NotificationUpdaterService.class);
    clickIntent.setAction(ACTION_UNDO);
    clickIntent.setPackage(packageName);
    putNotificationActionExtra(clickIntent, action);
    final PendingIntent clickPendingIntent = PendingIntent.getService(context, action.getNotificationId(),
            clickIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    undoView.setOnClickPendingIntent(R.id.status_bar_latest_event_content, clickPendingIntent);
    builder.setContent(undoView);

    // When the notification is cleared, we perform the destructive action
    final Intent deleteIntent = new Intent(context, NotificationUpdaterService.class);
    deleteIntent.setAction(ACTION_DESTRUCT);
    deleteIntent.setPackage(packageName);
    putNotificationActionExtra(deleteIntent, action);
    final PendingIntent deletePendingIntent = PendingIntent.getService(context, action.getNotificationId(),
            deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setDeleteIntent(deletePendingIntent);

    final Notification notification = builder.build();

    final NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(action.getNotificationId(), notification);

    sUndoNotifications.put(action.getNotificationId(), action);
    sNotificationTimestamps.put(action.getNotificationId(), action.mWhen);
}

From source file:com.afrozaar.jazzfestreporting.ResumableUpload.java

public static void showSelectableNotification(String videoId, Context context) {
    Log.d(TAG, String.format("Posting selectable notification for video ID [%s]", videoId));
    final NotificationManager notifyManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    Intent notificationIntent = new Intent(context, PlayActivity.class);
    notificationIntent.putExtra(MainActivity.YOUTUBE_ID, videoId);
    notificationIntent.setAction(Intent.ACTION_VIEW);

    URL url;//ww  w  . j  a va2 s.c  o  m
    try {
        url = new URL("https://i1.ytimg.com/vi/" + videoId + "/mqdefault.jpg");
        Bitmap thumbnail = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentTitle(context.getString(R.string.watch_your_video))
                .setContentText(context.getString(R.string.see_the_newly_uploaded_video))
                .setContentIntent(contentIntent).setSmallIcon(R.drawable.ic_stat_device_access_video)
                .setStyle(new NotificationCompat.BigPictureStyle().bigPicture(thumbnail));
        notifyManager.notify(PLAYBACK_NOTIFICATION_ID, builder.build());
        Log.d(TAG, String.format("Selectable notification for video ID [%s] posted", videoId));
    } catch (MalformedURLException e) {
        Log.e(TAG, e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }
}

From source file:ca.mcgill.hs.serv.LogFileUploaderService.java

@Override
public synchronized void onStart(final Intent intent, final int startId) {
    // Update the file list
    updateFileList();//from   w  ww  .  j  a v a  2  s .c  om

    // If there are no files, return.
    if (fileList.size() == 0 && !started) {
        makeToast(getResources().getString(R.string.uploader_no_new_files), Toast.LENGTH_SHORT);
        return;
    }

    // If it was already started, return. Else, continue.
    if (started) {
        return;
    }

    // At this point we consider the service to be started.
    started = true;

    registerReceiver(wifiOnlyPrefChanged, new IntentFilter(WIFI_ONLY_CHANGED_INTENT));
    registerReceiver(autoPrefChanged, new IntentFilter(AUTO_UPLOAD_CHANGED_INTENT));

    wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifiInfo = wifiMgr.getConnectionInfo();

    // Register completion receiver
    registerReceiver(completionReceiver, new IntentFilter(UPLOAD_COMPLETE_INTENT));

    // Connect to a network
    setUpConnection();

    notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_STRING);
    notificationMgr.cancel(NOTIFICATION_ID);

    final int icon = R.drawable.notification_icon;
    final String tickerText = getResources().getString(R.string.notification_ticker);
    final String contentTitle = getResources().getString(R.string.notification_upload_title);
    final String contentText = getResources().getString(R.string.notification_upload_text);

    final Notification n = new Notification(icon, tickerText, System.currentTimeMillis());

    final Intent i = new Intent(this, HSService.class);
    n.setLatestEventInfo(this, contentTitle, contentText,
            PendingIntent.getActivity(this.getBaseContext(), 0, i, PendingIntent.FLAG_CANCEL_CURRENT));

    notificationMgr.notify(NOTIFICATION_ID, n);

    filesUploaded = 0;
    uploadFiles();
}

From source file:com.google.android.apps.iosched.calendar.SessionAlarmService.java

private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd,
        final int snoozeMinutes) {
    Intent scheduleIntent = new Intent(SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, this,
            SessionAlarmService.class);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, snoozeMinutes * ONE_MINUTE_MILLIS);
    return PendingIntent.getService(this, 0, scheduleIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:net.xisberto.phonetodesktop.network.GoogleTasksService.java

private NotificationCompat.Builder buildNotification(int notif_id) {
    Builder builder = new NotificationCompat.Builder(this).setWhen(System.currentTimeMillis());
    // The default notification send the user to the waiting list
    Intent intentContent = new Intent(this, WaitListActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(WaitListActivity.class);
    stackBuilder.addNextIntent(intentContent);
    PendingIntent pendingContent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingContent);

    switch (notif_id) {
    case NOTIFICATION_SEND:
        builder.setSmallIcon(android.R.drawable.stat_sys_upload).setTicker(getString(R.string.txt_sending))
                .setContentTitle(getString(R.string.txt_sending));
        return builder;
    case NOTIFICATION_SEND_LATER:
        builder.setAutoCancel(true).setSmallIcon(android.R.drawable.stat_notify_error)
                .setTicker(getString(R.string.txt_error_no_connection))
                .setContentTitle(getString(R.string.txt_error_no_connection))
                .setContentText(getString(R.string.txt_error_try_again));
        return builder;
    case NOTIFICATION_ERROR:
        builder.setAutoCancel(true).setSmallIcon(android.R.drawable.stat_notify_error)
                .setTicker(getString(R.string.txt_error_sending))
                .setContentTitle(getString(R.string.txt_error_sending))
                .setContentText(getString(R.string.txt_error_try_again));
        return builder;
    case NOTIFICATION_NEED_AUTHORIZE:
        // When authorization is need, send the user to authorization
        // process
        intentContent.setClass(this, MainActivity.class);
        intentContent.setAction(Utils.ACTION_AUTHENTICATE);
        intentContent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingAuthorize = PendingIntent.getActivity(this, 0, intentContent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(pendingAuthorize).setAutoCancel(true)
                .setSmallIcon(android.R.drawable.stat_notify_error)
                .setTicker(getString(R.string.txt_error_sending))
                .setContentTitle(getString(R.string.txt_error_sending))
                .setContentText(getString(R.string.txt_need_authorize));
        return builder;

    default://  w  ww .j a v  a  2  s  .  c  om
        return null;
    }
}

From source file:org.chromium.chrome.browser.media.ui.MediaNotificationManager.java

private PendingIntent createPendingIntent(String action) {
    assert mService != null;
    Intent intent = createIntent(mService).setAction(action);
    return PendingIntent.getService(mService, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

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

private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd,
        final int snoozeMinutes) {
    Intent scheduleIntent = new Intent(SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, this,
            SessionAlarmService.class);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
    scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, snoozeMinutes * MILLI_ONE_MINUTE);
    return PendingIntent.getService(this, 0, scheduleIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.ubergeek42.WeechatAndroid.service.RelayServiceBackbone.java

/** build notification without displaying it
 *
 * @param tickerText text that flashes a bit, can be null
 * @param content text that appears under title
 * @param intent intent that's executed on notification click, can be null
 * @return built notification *//*from   ww  w.j av  a2  s  .  com*/

@TargetApi(16)
private Notification buildNotification(@Nullable String tickerText, @NonNull String content,
        @Nullable PendingIntent intent) {
    if (DEBUG_NOTIFICATIONS)
        logger.debug("buildNotification({}, {}, {})", new Object[] { tickerText, content, intent });
    PendingIntent contentIntent;
    contentIntent = (intent != null) ? intent
            : PendingIntent.getActivity(this, 0, new Intent(this, WeechatActivity.class),
                    PendingIntent.FLAG_CANCEL_CURRENT);

    int icon;
    if (!isConnection(AUTHENTICATED)) {
        if (isConnection(CONNECTING))
            icon = R.drawable.ic_connecting;
        else
            icon = R.drawable.ic_disconnected;
    } else if (hot_count == 0)
        icon = R.drawable.ic_connected;
    else
        icon = R.drawable.ic_hot;

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentIntent(contentIntent).setSmallIcon(icon)
            .setContentTitle("WeechatAndroid v" + BuildConfig.VERSION_NAME).setContentText(content)
            .setWhen(System.currentTimeMillis());

    if (prefs.getBoolean(PREF_NOTIFICATION_TICKER, true)) {
        builder.setTicker(tickerText);
    }

    Notification notification = builder.build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notification.priority = Notification.PRIORITY_MIN;
    }
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    return notification;
}