Example usage for android.app PendingIntent FLAG_UPDATE_CURRENT

List of usage examples for android.app PendingIntent FLAG_UPDATE_CURRENT

Introduction

In this page you can find the example usage for android.app PendingIntent FLAG_UPDATE_CURRENT.

Prototype

int FLAG_UPDATE_CURRENT

To view the source code for android.app PendingIntent FLAG_UPDATE_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

Usage

From source file:com.example.kyle.weatherforecast.MainActivity.java

private void postAlert(int i) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("Weather Alert!").setContentText(WeatherData.outlookArray[i])
            .setSmallIcon(R.drawable.small_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), WeatherData.symbolArray[i]))
            .setAutoCancel(true).setTicker("Wrap up warm!")
            // Heads-up and lock screen notifications
            .setVisibility(Notification.VISIBILITY_PUBLIC).setPriority(Notification.PRIORITY_HIGH)
            .setVibrate(new long[] { 100, 100, 100, 200, 200 }).setVibrate(new long[] { 0 })
            .setCategory(Notification.CATEGORY_ALARM);

    NotificationCompat.BigPictureStyle bigStyle = new NotificationCompat.BigPictureStyle();
    bigStyle.bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.snow_scene));
    builder.setStyle(bigStyle);/*w  w  w.  j av  a2  s  . c om*/

    Intent intent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class).addNextIntent(intent);
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationId, builder.build());

    notificationId++;
    Log.d(DEBUG_TAG, "ID: " + notificationId);
}

From source file:com.android.deskclock.alarms.AlarmNotifications.java

public static void showHighPriorityNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying high priority notification for alarm instance: " + instance.mId);

    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.alarm_alert_predismiss_title))
            .setContentText(AlarmUtils.getAlarmText(context, instance, true /* includeLabel */))
            .setSmallIcon(R.drawable.stat_notify_alarm).setAutoCancel(false).setOngoing(true)
            .setGroup(Integer.toString(instance.hashCode())).setGroupSummary(true)
            .setPriority(NotificationCompat.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setLocalOnly(true);

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.PREDISMISSED_STATE);
    notification.addAction(R.drawable.ic_alarm_off_24dp,
            context.getString(R.string.alarm_alert_dismiss_now_text), PendingIntent.getService(context,
                    instance.hashCode(), dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content action if instance is owned by alarm
    Intent viewAlarmIntent = createViewAlarmIntent(context, instance);
    notification.setContentIntent(PendingIntent.getActivity(context, instance.hashCode(), viewAlarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    nm.notify(instance.hashCode(), notification.build());
}

From source file:com.asburymotors.android.disneysocal.service.ListenerService.java

private void showNotification(Uri attractionsUri, ArrayList<DataMap> attractions) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();

    ConnectionResult connectionResult = googleApiClient.blockingConnect(Constants.GOOGLE_API_CLIENT_TIMEOUT_S,
            TimeUnit.SECONDS);/*from ww  w .  ja  v a 2  s .  c o m*/

    if (!connectionResult.isSuccess() || !googleApiClient.isConnected()) {
        Log.e(TAG, String.format(Constants.GOOGLE_API_CLIENT_ERROR_MSG, connectionResult.getErrorCode()));
        return;
    }

    Intent intent = new Intent(this, AttractionsActivity.class);
    // Pass through the data Uri as an extra
    intent.putExtra(Constants.EXTRA_ATTRACTIONS_URI, attractionsUri);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    int count = attractions.size();

    DataMap attraction = attractions.get(0);

    Bitmap bitmap = Utils.loadBitmapFromAsset(googleApiClient, attraction.getAsset(Constants.EXTRA_IMAGE));

    PendingIntent deletePendingIntent = PendingIntent.getService(this, 0,
            UtilityService.getClearRemoteNotificationsIntent(this), 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentText(getResources().getQuantityString(R.plurals.attractions_found, count, count))
            .setSmallIcon(R.mipmap.ic_launcher).setDeleteIntent(deletePendingIntent)
            .addAction(new NotificationCompat.Action.Builder(R.drawable.ic_full_explore,
                    getString(R.string.action_explore), pendingIntent).build())
            .extend(new NotificationCompat.WearableExtender().setBackground(bitmap)).build();

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(Constants.WEAR_NOTIFICATION_ID, notification);

    googleApiClient.disconnect();
}

From source file:com.raspi.chatapp.util.Notification.java

public void createNotification(String buddyId, String name, String message, String type) {
    SharedPreferences defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    if (defaultSharedPreferences
            .getBoolean(context.getResources().getString(R.string.pref_key_new_message_notifications), true)) {
        int index = buddyId.indexOf("@");
        if (index != -1)
            buddyId = buddyId.substring(0, index);
        if (name == null)
            name = buddyId;/*from   w  ww. j  a  v a  2s. com*/
        Log.d("DEBUG", "creating notification: " + buddyId + "|" + name + "|" + message);
        Intent resultIntent = new Intent(context, ChatActivity.class);
        resultIntent.setAction(NOTIFICATION_CLICK);
        String oldBuddyId = getOldBuddyId();
        Log.d("DEBUG",
                (oldBuddyId == null) ? ("oldBuddy is null (later " + buddyId) : ("oldBuddy: " + oldBuddyId));
        if (oldBuddyId == null || oldBuddyId.equals("")) {
            oldBuddyId = buddyId;
            setOldBuddyId(buddyId);
        }
        if (oldBuddyId.equals(buddyId)) {
            resultIntent.putExtra(Constants.BUDDY_ID, buddyId);
            resultIntent.putExtra(Constants.CHAT_NAME, name);
        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(ChatActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager nm = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
        NotificationCompat.Style style;

        String[] previousNotifications = readJSONArray(CURRENT_NOTIFICATIONS);
        String title;
        String[] currentNotifications = Arrays.copyOf(previousNotifications, previousNotifications.length + 1);
        currentNotifications[currentNotifications.length - 1] = name + ": " + message;
        if (previousNotifications.length == 0) {
            style = new NotificationCompat.BigTextStyle();
            NotificationCompat.BigTextStyle bigTextStyle = ((NotificationCompat.BigTextStyle) style);
            title = context.getResources().getString(R.string.new_message) + " "
                    + context.getResources().getString(R.string.from) + " " + name;
            bigTextStyle.bigText(currentNotifications[0]);
            bigTextStyle.setBigContentTitle(title);
        } else {
            style = new NotificationCompat.InboxStyle();
            NotificationCompat.InboxStyle inboxStyle = (NotificationCompat.InboxStyle) style;
            title = (previousNotifications.length + 1) + " "
                    + context.getResources().getString(R.string.new_messages);
            for (String s : currentNotifications)
                if (s != null && !"".equals(s))
                    inboxStyle.addLine(s);
            inboxStyle.setSummaryText(
                    (currentNotifications.length > 2) ? ("+" + (currentNotifications.length - 2) + " more")
                            : null);
            inboxStyle.setBigContentTitle(title);
        }
        writeJSONArray(currentNotifications, CURRENT_NOTIFICATIONS);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
                .setContentText(currentNotifications[currentNotifications.length - 1])
                .setSmallIcon(MessageHistory.TYPE_TEXT.equals(type) ? R.drawable.ic_forum_white_48dp
                        : R.drawable.ic_photo_camera_white_48dp)
                .setLargeIcon(getLargeIcon(Character.toUpperCase(name.toCharArray()[0]))).setStyle(style)
                .setAutoCancel(true).setPriority(5).setContentIntent(resultPendingIntent);

        String str = context.getResources().getString(R.string.pref_key_privacy);
        mBuilder.setVisibility(context.getResources().getString(R.string.pref_value1_privacy).equals(str)
                ? NotificationCompat.VISIBILITY_SECRET
                : context.getResources().getString(R.string.pref_value2_privacy).equals(str)
                        ? NotificationCompat.VISIBILITY_PRIVATE
                        : NotificationCompat.VISIBILITY_PUBLIC);

        str = context.getResources().getString(R.string.pref_key_vibrate);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setVibrate(new long[] { 800, 500, 800, 500 });

        str = context.getResources().getString(R.string.pref_key_led);
        if (defaultSharedPreferences.getBoolean(str, true))
            mBuilder.setLights(Color.BLUE, 500, 500);

        str = defaultSharedPreferences.getString(context.getResources().getString(R.string.pref_key_ringtone),
                "");
        mBuilder.setSound("".equals(str) ? RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                : Uri.parse(str));

        nm.notify(NOTIFICATION_ID, mBuilder.build());
        str = context.getResources().getString(R.string.pref_key_banner);
        if (!defaultSharedPreferences.getBoolean(str, true)) {
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
            }
            reset();
        }
    }
}

From source file:com.scoreflex.ScoreflexGcmClient.java

protected static PendingIntent buildPendingIntent(JSONObject scoreflexData, Context context,
        Class<? extends Activity> activity) {
    Intent resultIntent = new Intent(context, activity);

    resultIntent.putExtra(Scoreflex.NOTIFICATION_EXTRA_KEY, scoreflexData.toString());

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(activity);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    return resultPendingIntent;
}

From source file:com.campusconnect.MyFirebaseMessagingService.java

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 *//*from   ww  w .  j  ava  2s  .c  o m*/
private void sendNotification(String title, String messageBody, String type, String id) {
    Intent intent = new Intent(this, HomeActivity2.class);
    Log.i("sw32notification", id + ":" + type + ":" + messageBody);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setAction(Long.toString(System.currentTimeMillis()));
    intent.putExtra("pendingIntentAction", "Clear Notifications");
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    inboxStyle = new NotificationCompat.InboxStyle();
    int i = 0;
    for (CustomNotification customNotification : new ArrayList<>(
            CustomNotification.listAll(CustomNotification.class))) {
        Log.i("sw32", "here notification");
        i++;
        inboxStyle.addLine(customNotification.getTitle() + " - " + customNotification.getMessageBody());
    }
    inboxStyle.setSummaryText("Campus Connect");
    notificationBuilder.setSmallIcon(R.mipmap.ccnoti)
            .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ccnoti))
            .setContentTitle("Campus Connect").setContentText(i + " New notifications").setStyle(inboxStyle)
            .setGroup(CC).setGroupSummary(true).setSound(defaultSoundUri).setAutoCancel(true)
            .setContentIntent(pendingIntent);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(notifyId /*(int) System.currentTimeMillis()*/ /* ID of notification */,
            notificationBuilder.build());

}

From source file:com.actinarium.nagbox.service.NotificationHelper.java

private static void fireForMultipleTasks(Context context, Task[] tasks) {
    long currentTime = System.currentTimeMillis();
    final NotificationManagerCompat notifManager = NotificationManagerCompat.from(context);
    final int tasksCount = tasks.length;

    // Create a group of stacked notifications
    for (Task task : tasks) {

        // Notification action to stop the task
        Intent stopAction = new Intent(context, NagboxService.class);
        stopAction.setAction(NagboxService.ACTION_ON_NOTIFICATION_ACTION_STOP_TASK);
        stopAction.putExtra(NagboxService.EXTRA_TASK_ID, task.id);
        stopAction.putExtra(NagboxService.EXTRA_CANCEL_NOTIFICATION_ID, (int) task.id);

        // Since actions are "equal" (differ in extras only), need to use a unique "request code" (task.id will do)
        PendingIntent stopActionPI = PendingIntent.getService(context, (int) task.id, stopAction,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Notification stackedItem = makeCommonBuilder(context, currentTime, task.id).setContentTitle(task.title)
                .setContentText(DateUtils.prettyPrintNagDuration(context, task.lastStartedAt, currentTime))
                .setGroup(NAG_NOTIFICATION_GROUP).addAction(R.drawable.ic_cancel,
                        context.getString(R.string.notification_action_stop), stopActionPI)
                .build();//from w  w  w. j ava  2s  .  c  o m

        // Well, let's use task IDs for their individual notifications then
        notifManager.notify((int) task.id, stackedItem);
    }

    // Summary text, reused
    final String summary = context.getResources().getQuantityString(R.plurals.notification_stacked_header,
            tasksCount, tasksCount);

    // Public summary notification
    // Since Android N already shows app name in the notification, display the summary in title
    boolean isApi24 = Build.VERSION.SDK_INT >= 24;
    Notification publicNotification = makeCommonBuilder(context, currentTime, Task.NO_ID)
            .setContentTitle(isApi24 ? summary : context.getString(R.string.app_name))
            .setContentText(isApi24 ? null : summary).setGroup(NAG_NOTIFICATION_GROUP).setGroupSummary(true)
            .build();

    // Create expanded (inbox style) for private notification.
    // If there are more than 5 tasks, enlist first 4 and add +x more
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(summary);
    if (tasksCount <= 5) {
        for (Task task : tasks) {
            inboxStyle.addLine(makeInboxStyleLine(context, task, currentTime));
        }
    } else {
        for (int i = 0; i < 4; i++) {
            inboxStyle.addLine(makeInboxStyleLine(context, tasks[i], currentTime));
        }
        inboxStyle.addLine(context.getString(R.string.notification_stack_overflow, tasksCount - 4));
    }

    // Create private summary notification
    Notification privateNotification = makeCommonBuilder(context, currentTime, Task.NO_ID)
            .setPublicVersion(publicNotification)
            .setContentTitle(isApi24 ? summary : context.getString(R.string.app_name))
            .setContentText(isApi24 ? null : summary).setStyle(inboxStyle).setGroup(NAG_NOTIFICATION_GROUP)
            .setGroupSummary(true).build();

    notifManager.notify(NAG_NOTIFICATION_ID, privateNotification);
}

From source file:com.amlcurran.messages.notifications.NotificationActionBuilder.java

public NotificationCompat.Action buildLinkAction(Link link) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(link.get());/*  w  ww  . j  a  va 2 s . c  om*/
    PendingIntent linkIntent = PendingIntent.getActivity(context, 12123, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    String label = context.getString(R.string.open_link);
    return new NotificationCompat.Action.Builder(R.drawable.ic_website, label, linkIntent).build();
}

From source file:au.com.wallaceit.reddinator.MailCheckService.java

private void setNotification() {
    int message = global.mRedditData.getInboxCount();
    Intent notifyIntent = new Intent(this, WebViewActivity.class);
    notifyIntent.setAction(WebViewActivity.ACTION_CLEAR_INBOX_COUNT);
    notifyIntent.putExtra("url", "http://www.reddit.com/message/unread/.compact");
    Notification notification = new NotificationCompat.Builder(this).setContentTitle(message + " New Messages")
            .setContentText("Click to view reddit messages")
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.reddit_icon_small))
            .setSmallIcon(R.drawable.ic_notify)
            .setContentIntent(/*from   ww w .j a v a2s.com*/
                    PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT))
            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);
}

From source file:net.frygo.findmybuddy.GCMIntentService.java

private static void generateNotification(Context context, String message) {

    Random rand = new Random();
    int x = rand.nextInt();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, customlistview.class);
    notificationIntent.putExtra("alert", message);
    message = message + " would like to add you as friend";
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification = new Notification(R.drawable.logo, message, System.currentTimeMillis());
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(x, notification);

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock mWakelock = pm
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, title);
    mWakelock.acquire();/*from   w  w w  . jav  a 2 s. c  o m*/

    // Timer before putting Android Device to sleep mode.
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            mWakelock.release();
        }
    };
    timer.schedule(task, 5000);

}