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.bluelinelabs.logansquare.typeconverters.PendingIntentConverter.java

@Override
public void serialize(PendingIntent pendingIntent, String fieldName, boolean writeFieldNameForObject,
        JsonGenerator jsonGenerator) throws IOException {
    android.util.Log.d("json2notification", "PendingIntentConverter:serialize");
    if (pendingIntent == null)
        return;//from w  ww. j  a v  a 2s .  co m
    SimplePendingIntent simplePendingIntent = new SimplePendingIntent();
    simplePendingIntent.requestCode = 0;
    simplePendingIntent.flags = PendingIntent.FLAG_UPDATE_CURRENT;
    //simplePendingIntent.intent = pendingIntent.getIntent(); // hidden-api
    simplePendingIntent.intent = getIntent(pendingIntent);
    // pendingIntent.isActivity(); // hidden-api
    boolean isActivity = isActivity(pendingIntent);
    if (isActivity) {
        simplePendingIntent.getActivity = true;
    } else {
        simplePendingIntent.getService = true;
    }
    if (writeFieldNameForObject)
        jsonGenerator.writeFieldName(fieldName);
    SimplePendingIntent$$JsonObjectMapper._serialize((SimplePendingIntent) simplePendingIntent, jsonGenerator,
            true);
}

From source file:com.chess.genesis.net.GenesisNotifier.java

public static void ScheduleWakeup(final Context context) {
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, Pref.getInt(context, R.array.pf_notifierPolling));
    final long start = cal.getTimeInMillis();
    final long interval = start - System.currentTimeMillis();

    final Intent intent = new Intent(context, GenesisAlarm.class);
    final PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, start, interval, pintent);
}

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

private PendingIntent callPendingIntent(PhoneNumber number) {
    Uri telUri = Uri.parse("tel:" + number.flatten());
    Intent intent = new Intent(Intent.ACTION_CALL);
    intent.setData(telUri);/*from www.  j av  a  2  s  . c  o  m*/
    return PendingIntent.getActivity(context, 12121, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:com.capstone.transit.trans_it.RouteMap.java

@Override
protected void onPause() {
    super.onPause();
    stopService(positionsServiceIntent);
    positionsServiceIntent = new Intent(getApplicationContext(), RefreshPositionsService.class);
    final PendingIntent pendingIntent = PendingIntent.getService(this, 0, positionsServiceIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pendingIntent);//from  w ww .  j ava 2 s  .  com
}

From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java

@Override
public void onCreate() {
    super.onCreate();
    contentResolver = getContentResolver();
    cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    sharedPreferences = getSharedPreferences(PlacesConstants.SHARED_PREFERENCE_FILE, Context.MODE_PRIVATE);
    sharedPreferencesEditor = sharedPreferences.edit();
    sharedPreferenceSaver = PlatformSpecificImplementationFactory.getSharedPreferenceSaver(this);

    Intent retryIntent = new Intent(PlacesConstants.RETRY_QUEUED_CHECKINS_ACTION);
    retryQueuedCheckinsPendingIntent = PendingIntent.getBroadcast(this, 0, retryIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
}

From source file:com.bccs.bsecure.MessageReceivedNotification.java

/**
 * Shows the notification, or updates a previously shown notification of
 * this type, with the given parameters.
 * <p>/*  w  w  w. j a va  2  s.  c o m*/
 * Customize this method's arguments to present relevant content in
 * the notification.
 * <p>
 * Customize the contents of this method to tweak the behavior and
 * presentation of message received notifications. Make
 * sure to follow the
 * <a href="https://developer.android.com/design/patterns/notifications.html">
 * Notification design guidelines</a> when doing so.
 *
 * @see #cancel(Context)
 */
public static void notify(final Context context, final String title, final String body) {
    final Resources res = context.getResources();

    // This image is used as the notification's large icon (thumbnail).
    // Remove this if your notification has no relevant thumbnail.
    final Bitmap picture = BitmapFactory.decodeResource(res, R.drawable.ic_security_black_48dp);

    final String text = body;
    //Intent conversationIntent = new Intent("com.bccs.bsecure.recentconversation");
    Intent conversationIntent = new Intent(context, Conversation.class);

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

            // Set appropriate defaults for the notification light, sound,
            // and vibration.
            .setDefaults(Notification.DEFAULT_ALL)

            // Set required fields, including the small icon, the
            // notification title, and text.
            .setSmallIcon(R.drawable.ic_security_black_48dp).setContentTitle(title).setContentText(text)

            // All fields below this line are optional.

            // Use a default priority (recognized on devices running Android
            // 4.1 or later)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)

            // Provide a large icon, shown with the notification in the
            // notification drawer on devices running Android 3.0 or later.
            .setLargeIcon(picture)

            // If this notification relates to a past or upcoming event, you
            // should set the relevant time information using the setWhen
            // method below. If this call is omitted, the notification's
            // timestamp will by set to the time at which it was shown.
            // Call setWhen if this notification relates to a past or
            // upcoming event. The sole argument to this method should be
            // the notification timestamp in milliseconds.
            //.setWhen(...)

            // Set the pending intent to be initiated when the user touches
            // the notification.
            .setContentIntent(PendingIntent.getActivity(context, 0, conversationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT))

            // Show expanded text content on devices running Android 4.1 or
            // later.
            .setStyle(new NotificationCompat.BigTextStyle().bigText(text).setBigContentTitle(title)
                    .setSummaryText(body))

            // Automatically dismiss the notification when it is touched.
            .setAutoCancel(true);

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

From source file:co.carlosjimenez.android.currencyalerts.app.widget.DetailWidgetProvider.java

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // Perform this loop procedure for each App Widget that belongs to this provider

    for (int appWidgetId : appWidgetIds) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_detail);

        // Create an Intent to launch MainActivity
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.widget, pendingIntent);

        // Set up the header
        setMainCurrencyDetails(context, views, appWidgetIds);

        // Set up the collection
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            setRemoteAdapter(context, views, appWidgetIds);
        } else {/*from  ww  w.  ja v  a2s  . c  o m*/
            setRemoteAdapterV11(context, views, appWidgetIds);
        }
        Intent clickIntentTemplate = new Intent(context, DetailActivity.class);

        PendingIntent clickPendingIntentTemplate = TaskStackBuilder.create(context)
                .addNextIntentWithParentStack(clickIntentTemplate)
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setPendingIntentTemplate(R.id.widget_list, clickPendingIntentTemplate);
        views.setEmptyView(R.id.widget_list, R.id.widget_empty);

        // Tell the AppWidgetManager to perform an update on the current app widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

From source file:com.keylesspalace.tusky.util.NotificationManager.java

/**
 * Takes a given Mastodon notification and either creates a new Android notification or updates
 * the state of the existing notification to reflect the new interaction.
 *
 * @param context  to access application preferences and services
 * @param notifyId an arbitrary number to reference this notification for any future action
 * @param body     a new Mastodon notification
 *///from   ww w . j a v  a  2  s. c om
public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;
    }

    createNotificationChannels(context);

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).apply();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, getChannelId(body))
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setColor(ContextCompat.getColor(context, (R.color.primary)))
            .setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    setupPreferences(preferences, builder);

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        //load the avatar synchronously
        Bitmap accountAvatar;
        try {
            accountAvatar = Picasso.with(context).load(body.account.avatar)
                    .transform(new RoundedTransformation(7, 0)).get();
        } catch (IOException e) {
            Log.d(TAG, "error loading account avatar", e);
            accountAvatar = BitmapFactory.decodeResource(context.getResources(), R.drawable.avatar_default);
        }

        builder.setLargeIcon(accountAvatar);

    } else {
        try {
            String format = context.getString(R.string.notification_title_summary);
            String title = String.format(format, currentNotifications.length());
            String text = truncateWithEllipses(joinNames(context, currentNotifications), 40);
            builder.setContentTitle(title).setContentText(text);
        } catch (JSONException e) {
            Log.d(TAG, Log.getStackTraceString(e));
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    android.app.NotificationManager notificationManager = (android.app.NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    //noinspection ConstantConditions
    notificationManager.notify(notifyId, builder.build());
}

From source file:net.olejon.mdapp.NotificationsFromSlvIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final Context mContext = this;

    final MyTools mTools = new MyTools(mContext);

    if (mTools.getDefaultSharedPreferencesBoolean("NOTIFICATIONS_FROM_SLV_NOTIFY")
            && mTools.isDeviceConnected()) {
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        int projectVersionCode = mTools.getProjectVersionCode();

        String device = mTools.getDevice();

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                getString(R.string.project_website_uri) + "api/1/notifications-from-slv/?first&version_code="
                        + projectVersionCode + "&device=" + device,
                new Response.Listener<JSONArray>() {
                    @SuppressLint("InlinedApi")
                    @Override/* w  w w . j av  a  2s.co  m*/
                    public void onResponse(JSONArray response) {
                        try {
                            final JSONObject notifications = response.getJSONObject(0);

                            final String title = notifications.getString("title");
                            final String message = notifications.getString("message");

                            final String lastTitle = mTools
                                    .getSharedPreferencesString("NOTIFICATIONS_FROM_SLV_LAST_TITLE");

                            if (!title.equals(lastTitle)) {
                                if (!lastTitle.equals("")) {
                                    Intent launchIntent = new Intent(mContext,
                                            NotificationsFromSlvActivity.class);
                                    PendingIntent launchPendingIntent = PendingIntent.getActivity(mContext, 0,
                                            launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                            R.drawable.ic_launcher);

                                    NotificationManagerCompat notificationManager = NotificationManagerCompat
                                            .from(mContext);
                                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                            mContext);

                                    notificationBuilder.setWhen(mTools.getCurrentTime())
                                            .setPriority(Notification.PRIORITY_HIGH)
                                            .setVisibility(Notification.VISIBILITY_PUBLIC)
                                            .setCategory(Notification.CATEGORY_MESSAGE).setLargeIcon(bitmap)
                                            .setSmallIcon(R.drawable.ic_local_hospital_white_24dp)
                                            .setSound(RingtoneManager
                                                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                            .setLights(Color.BLUE, 1000, 2000).setTicker(title)
                                            .setContentTitle(title).setContentText(message)
                                            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                                            .setContentIntent(launchPendingIntent)
                                            .addAction(R.drawable.ic_notifications_white_24dp,
                                                    getString(
                                                            R.string.service_notifications_from_slv_read_more),
                                                    launchPendingIntent);

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

                                mTools.setSharedPreferencesString("NOTIFICATIONS_FROM_SLV_LAST_TITLE", title);
                            }
                        } catch (Exception e) {
                            Log.e("NotificationsFromSlv", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("NotificationsFromSlv", error.toString());
                    }
                });

        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonArrayRequest);
    }
}

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

static synchronized void showLowPriorityNotification(Context context, AlarmInstance instance) {
    LogUtils.v("Displaying low priority notification for alarm instance: " + instance.mId);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setShowWhen(false)
            .setContentTitle(// w w  w  .jav  a  2s . com
                    context.getString(com.androidinspain.deskclock.R.string.alarm_alert_predismiss_title))
            .setContentText(AlarmUtils.getAlarmText(context, instance, true /* includeLabel */))
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background))
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm).setAutoCancel(false)
            .setSortKey(createSortKey(instance)).setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);

    if (Utils.isNOrLater()) {
        builder.setGroup(UPCOMING_GROUP_KEY);
    }

    // Setup up hide notification
    Intent hideIntent = AlarmStateManager.createStateChangeIntent(context, AlarmStateManager.ALARM_DELETE_TAG,
            instance, AlarmInstance.HIDE_NOTIFICATION_STATE);
    final int id = instance.hashCode();
    builder.setDeleteIntent(
            PendingIntent.getService(context, id, hideIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup up dismiss action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.PREDISMISSED_STATE);
    builder.addAction(com.androidinspain.deskclock.R.drawable.ic_alarm_off_24dp,
            context.getString(com.androidinspain.deskclock.R.string.alarm_alert_dismiss_text),
            PendingIntent.getService(context, id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

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

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    final Notification notification = builder.build();
    nm.notify(id, notification);
    updateUpcomingAlarmGroupNotification(context, -1, notification);
}