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:br.com.bioscada.apps.biotracks.io.sendtogoogle.SendToGoogleUtils.java

/**
 * Sends a notification to request permission.
 * /*from w w  w .j a  v  a 2 s . c o  m*/
 * @param context the context
 * @param accountName the account name
 * @param intent the intent
 * @param notificaitonId the notification id
 */
public static void sendNotification(Context context, String accountName, Intent intent, int notificaitonId) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_FROM_BACKGROUND);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setContentText(context.getString(R.string.permission_request_message, accountName))
            .setContentTitle(context.getString(R.string.permission_request_title))
            .setSmallIcon(android.R.drawable.ic_dialog_alert)
            .setTicker(context.getString(R.string.permission_request_title));
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificaitonId, builder.build());
}

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

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

    NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
            .setContentTitle(instance.getLabelOrDefault(context))
            .setContentText(context.getString(R.string.alarm_alert_snooze_until,
                    AlarmUtils.getFormattedTime(context, instance.getAlarmTime())))
            .setSmallIcon(R.drawable.stat_notify_alarm).setAutoCancel(false).setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MAX).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.DISMISSED_STATE);
    notification.addAction(R.drawable.ic_alarm_off_24dp, context.getString(R.string.alarm_alert_dismiss_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:org.andicar.service.UpdateCheckService.java

private void setNextRun() {
    Calendar cal = Calendar.getInstance();
    if (cal.get(Calendar.HOUR_OF_DAY) >= 18)
        cal.add(Calendar.DAY_OF_YEAR, 1);
    cal.set(Calendar.HOUR_OF_DAY, 20);
    cal.set(Calendar.MINUTE, 0);/*from   w w  w.j a  va2 s. co  m*/
    Intent i = new Intent(this, UpdateCheckService.class);
    PendingIntent pIntent = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC, cal.getTimeInMillis(), pIntent);
}

From source file:com.molice.oneingdufs.androidpn.Notifier.java

public void notify(String notificationId, String apiKey, String title, String message, String uri) {
    Log.d(LOGTAG, "notify()...");

    Log.d(LOGTAG, "notificationId=" + notificationId);
    Log.d(LOGTAG, "notificationApiKey=" + apiKey);
    Log.d(LOGTAG, "notificationTitle=" + title);
    Log.d(LOGTAG, "notificationMessage=" + message);
    Log.d(LOGTAG, "notificationUri=" + uri);

    if (SettingsActivity.getNotificationEnabled(context)) {
        // Show the toast
        //            if (isNotificationToastEnabled()) {
        //                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        //            }

        // Notification
        Notification notification = new Notification();
        notification.icon = getNotificationIcon();
        //            notification.defaults = Notification.DEFAULT_LIGHTS;
        if (SettingsActivity.getNotificationSound(context)) {
            notification.defaults |= Notification.DEFAULT_SOUND;
        }/*from w w w .ja  va2  s  .  co  m*/
        if (SettingsActivity.getNotificationVibrate(context)) {
            notification.defaults |= Notification.DEFAULT_VIBRATE;
        }
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.when = System.currentTimeMillis();
        notification.tickerText = message;

        //            Intent intent;
        //            if (uri != null
        //                    && uri.length() > 0
        //                    && (uri.startsWith("http:") || uri.startsWith("https:")
        //                            || uri.startsWith("tel:") || uri.startsWith("geo:"))) {
        //                intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        //            } else {
        //                String callbackActivityPackageName = sharedPrefs.getString(
        //                        Constants.CALLBACK_ACTIVITY_PACKAGE_NAME, "");
        //                String callbackActivityClassName = sharedPrefs.getString(
        //                        Constants.CALLBACK_ACTIVITY_CLASS_NAME, "");
        //                intent = new Intent().setClassName(callbackActivityPackageName,
        //                        callbackActivityClassName);
        //                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            }

        Intent intent = new Intent(context, MessageDetailActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        JSONObject data = formatMetaFromTitle(title);
        try {
            data.putOpt("id", notificationId);
            data.putOpt("content", message);
        } catch (Exception e) {
            Log.d("JSON", "Notifier#notify, e=" + e.toString());
        }
        intent.putExtra("data", data.toString());
        intent.putExtra("fromNotification", true);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        //            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(context, random.nextInt(), intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(context, data.optString("title"), message, contentIntent);
        notificationManager.notify(random.nextInt(), notification);

        //            Intent clickIntent = new Intent(
        //                    Constants.ACTION_NOTIFICATION_CLICKED);
        //            clickIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
        //            clickIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
        //            clickIntent.putExtra(Constants.NOTIFICATION_TITLE, title);
        //            clickIntent.putExtra(Constants.NOTIFICATION_MESSAGE, message);
        //            clickIntent.putExtra(Constants.NOTIFICATION_URI, uri);
        //            //        positiveIntent.setData(Uri.parse((new StringBuilder(
        //            //                "notif://notification.adroidpn.org/")).append(apiKey).append(
        //            //                "/").append(System.currentTimeMillis()).toString()));
        //            PendingIntent clickPendingIntent = PendingIntent.getBroadcast(
        //                    context, 0, clickIntent, 0);
        //
        //            notification.setLatestEventInfo(context, title, message,
        //                    clickPendingIntent);
        //
        //            Intent clearIntent = new Intent(
        //                    Constants.ACTION_NOTIFICATION_CLEARED);
        //            clearIntent.putExtra(Constants.NOTIFICATION_ID, notificationId);
        //            clearIntent.putExtra(Constants.NOTIFICATION_API_KEY, apiKey);
        //            //        negativeIntent.setData(Uri.parse((new StringBuilder(
        //            //                "notif://notification.adroidpn.org/")).append(apiKey).append(
        //            //                "/").append(System.currentTimeMillis()).toString()));
        //            PendingIntent clearPendingIntent = PendingIntent.getBroadcast(
        //                    context, 0, clearIntent, 0);
        //            notification.deleteIntent = clearPendingIntent;
        //
        //            notificationManager.notify(random.nextInt(), notification);

    } else {
        Log.w(LOGTAG, "Notificaitons disabled.");
    }
}

From source file:com.gdglab.iot.gcm.GcmIntentService.java

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

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, GdglabActivity.class);

    resultIntent.putExtra("msgText", msg);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    //Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(GdglabActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_gcm).setContentTitle("GCM Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
    mBuilder.setContentIntent(resultPendingIntent);

    Notification note = mBuilder.build();

    note.flags |= Notification.FLAG_AUTO_CANCEL;

    mNotificationManager.notify(NOTIFICATION_ID, note);
}

From source file:co.vanir.indecentxposure.IndecentXposure.java

public static void notify(final Context context, final String exampleString) {
    final Resources res = context.getResources();

    final String ticker = exampleString;
    final String title = res.getString(R.string.solve_problems_notification_title); //_template, exampleString);
    final String text = res.getString(R.string.solve_problems_notification_placeholder_text_template);//, exampleString);

    //one button opens the "uninstall app" settings page
    final Intent removeIntent = new Intent();
    removeIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", SerialOffender.getPackageName(), null);
    removeIntent.setData(uri);/*from   w w w . ja v  a  2  s .  c om*/

    //the other option will hide the notification until the user uninstalls and reinstalls
    //  the installer
    final Intent ignoreIntent = new Intent();
    ignoreIntent.setAction("co.vanir.indecentxposure.IGNORE_LIKELY_FUNK");

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_stat_solve_problems).setContentTitle(title).setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_MAX).setTicker(ticker)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(text).setBigContentTitle(title)
                    .setSummaryText(res.getString(R.string.summary_thanks)))
            .addAction(0, res.getString(R.string.action_remove),
                    PendingIntent.getActivity(context, 0, removeIntent, PendingIntent.FLAG_UPDATE_CURRENT))
            .addAction(0, res.getString(R.string.action_accept_consequences),
                    PendingIntent.getBroadcast(context, 0, ignoreIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    notify(context, builder.build(), true);
}

From source file:cl.telematica.android.alimentame.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *//*w ww  . ja va 2s.  co m*/
private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.mipmap.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .setColor(Color.RED).setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setVibrate(new long[] { 100, 250, 100, 500 })
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:com.akaashvani.akaashvani.geofence.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *//*from   ww w.  j  a v a 2 s  .  c o  m*/
private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), TabActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(TabActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.drawable.me)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.me)).setColor(Color.RED)
            .setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:de.appplant.cordova.plugin.background.ForegroundService.java

/**
 * Create a notification as the visible part to be able to put the service
 * in a foreground state./*from  w ww  .  j  ava2s .com*/
 *
 * @return
 *      A local ongoing notification which pending intent is bound to the
 *      main activity.
 */
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Notification makeNotification() {
    JSONObject settings = BackgroundMode.getSettings();
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);

    notification = new Notification.Builder(context).setContentTitle(settings.optString("title", ""))
            .setContentText(settings.optString("text", "")).setTicker(settings.optString("ticker", ""))
            .setOngoing(true).setSmallIcon(getIconResId());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (settings.optBoolean("isPublic") == true) {
            notification.setVisibility(Notification.VISIBILITY_PUBLIC);
        }

        if (!settings.optString("color").equals("")) {
            try {
                notification.setColor(Color.parseColor(settings.optString("color")));
            } catch (Exception e) {
                Log.e("BackgroundMode", settings.optString("color") + " is not a valid color");
            }
        }
    }

    if (intent != null && settings.optBoolean("resume")) {

        PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setContentIntent(contentIntent);
    }

    if (Build.VERSION.SDK_INT < 16) {
        // Build notification for HoneyComb to ICS
        return notification.getNotification();
    } else {
        // Notification for Jellybean and above
        return notification.build();
    }
}

From source file:com.andrada.sitracker.tasks.ImportAuthorsTask.java

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    if (intent == null) {
        return;/*w  w  w  .  ja v  a  2s.  co  m*/
    }
    setupExtras(intent);

    this.importProgress = new ImportProgress(authorsList.size());

    //Filter out duplicates right away
    try {
        List<String> urlIds = helper.getAuthorDao().getAuthorsUrlIds();
        Map<String, String> prospectAuthorIds = new HashMap<String, String>();
        for (String auth : authorsList) {
            prospectAuthorIds.put(SamlibPageHelper.getUrlIdFromCompleteUrl(auth), auth);
        }
        for (String urlId : urlIds) {
            if (prospectAuthorIds.containsKey(urlId)) {
                authorsList.remove(prospectAuthorIds.get(urlId));
                this.importProgress.importFail(urlId);
            }
        }
        if (authorsList.size() == 0) {
            EventBus.getDefault().post(new ImportUpdates(this.importProgress));
        }
    } catch (SQLException e) {
        LOGW(TAG, "Failed to filter out duplicate authors", e);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(android.R.drawable.stat_notify_sync).setOngoing(true).setAutoCancel(false)
            .setContentTitle(getResources().getString(R.string.notification_import_title)).setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, ImportAuthorsActivity_.class);
    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ImportAuthorsActivity_.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    for (String authUrl : authorsList) {
        try {
            if (shouldCancel) {
                //Make sure to cancel it here as well
                notificationManager.cancel(NOTIFICATION_ID);
                break;
            }
            SiteStrategy strategy = SiteDetector.chooseStrategy(authUrl, helper);
            if (strategy == null) {
                this.importProgress.importFail(authUrl);
            } else {
                int returnMsg = strategy.addAuthorForUrl(authUrl);
                if (returnMsg == -1) {
                    this.importProgress.importSuccess();
                } else {
                    this.importProgress.importFail(authUrl);
                }
            }

            if (shouldCancel) {
                //Make sure to cancel it here as well
                notificationManager.cancel(NOTIFICATION_ID);
                break;
            }
            EventBus.getDefault().post(new ImportUpdates(new ImportProgress(this.importProgress)));
            mBuilder.setContentText(getResources().getString(R.string.notification_import_progress,
                    importProgress.getTotalProcessed(), importProgress.getTotalAuthors())).setAutoCancel(false)
                    .setProgress(importProgress.getTotalAuthors(), importProgress.getTotalProcessed(), false);
            notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
            //Sleep for 5 seconds to avoid ban
            Thread.sleep(5000);

            if (!shouldCancel) {
                EventBus.getDefault().post(new ImportUpdates(this.importProgress));
            }
        } catch (InterruptedException e) {
            LOGW(TAG, "Importing was forcibly stopped", e);
        }
    }
    if (!shouldCancel) {
        Intent finishIntent = HomeActivity_.intent(this).authorsProcessed(importProgress.getTotalAuthors())
                .authorsSuccessfullyImported(importProgress.getSuccessfullyImported()).get();
        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(HomeActivity_.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(finishIntent);

        BackupManager bm = new BackupManager(this);
        bm.dataChanged();

        AnalyticsHelper.getInstance().sendEvent(Constants.GA_ADMIN_CATEGORY, Constants.GA_EVENT_AUTHOR_IMPORT,
                Constants.GA_EVENT_IMPORT_COMPLETE, importProgress.getTotalAuthors());

        mBuilder.setProgress(0, 0, false).setOngoing(false).setAutoCancel(true)
                .setContentText(getResources().getString(R.string.notification_import_complete))
                .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
        notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}