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:org.ohmage.sync.OhmageSyncAdapter.java

private void showInstallApkNotification(int id, Builder builder, Intent intent) {
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(getContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(resultPendingIntent).setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL);

    NotificationManager mNotificationManager = (NotificationManager) getContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(id, builder.build());
}

From source file:org.c99.SyncProviderDemo.EventosSyncAdapterService.java

private static void generateNotification(Evento evento, Context context) {
    NotificationManager mNotificationManager;
    int numMessages = 0;
    Log.i("Start", "notification");

    /* Invoking the default notification service */
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);

    mBuilder.setContentTitle("Novo evento");
    mBuilder.setContentText(evento.getNome());
    mBuilder.setTicker("Evento !!!");
    mBuilder.setSmallIcon(R.drawable.logo);

    /* Increase notification number every time a new notification arrives */
    mBuilder.setNumber(++numMessages);/*ww  w  .  j a  va 2 s  .c  om*/

    /* Creates an explicit intent for an Activity in your app */
    Intent resultIntent = new Intent(context, NavigationDrawer.class);
    resultIntent.setAction("EVENTO"); //tentando linkar
    Bundle bundle = new Bundle();
    bundle.putSerializable("evento", evento);
    resultIntent.putExtras(bundle);
    // fim arrumar a inteao

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NavigationDrawer.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);

    mNotificationManager =
            //                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            //                (NotificationManager) getActivity().getApplication().
            //                        getSystemService(getActivity().getApplication().NOTIFICATION_SERVICE);

            /* notificationID allows you to update the notification later on. */
            //                (NotificationManager) getApplication().getSystemService(NOTIFICATION_SERVICE);
            (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    mNotificationManager.notify(evento.getCodigo(), mBuilder.build());
}

From source file:com.android.mms.transaction.MessagingNotification.java

public static void blockingUpdateNewIccMessageIndicator(Context context, String address, String message,
        int subId, long timeMillis) {
    final Notification.Builder noti = new Notification.Builder(context).setWhen(timeMillis);
    Contact contact = Contact.get(address, false);
    NotificationInfo info = getNewIccMessageNotificationInfo(context, true /* isSms */, address, message,
            null /* subject */, subId, timeMillis, null /* attachmentBitmap */, contact, WorkingMessage.TEXT);
    noti.setSmallIcon(R.drawable.stat_notify_sms);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    //        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    // Update the notification.
    PendingIntent pendingIntent;/*  w  ww.j  ava  2 s. com*/
    if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
        pendingIntent = PendingIntent.getActivity(context, 0, info.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    } else {
        // Use requestCode to avoid updating all intents of previous notifications
        pendingIntent = PendingIntent.getActivity(context, ICC_NOTIFICATION_ID_BASE + subId, info.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    String title = info.mTitle;
    noti.setContentTitle(title).setContentIntent(pendingIntent)
            //taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
            .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT);

    int defaults = 0;
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    boolean vibrate = false;
    if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
        // The most recent change to the vibrate preference is to store a boolean
        // value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
        // first.
        vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false);
    } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
        // This is to support the pre-JellyBean MR1.1 version of vibrate preferences
        // when vibrate was a tri-state setting. As soon as the user opens the Messaging
        // app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
        // to the boolean value stored in NOTIFICATION_VIBRATE.
        String vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
        vibrate = "always".equals(vibrateWhen);
    }
    if (vibrate) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }
    String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
    noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
    Log.d(TAG, "blockingUpdateNewIccMessageIndicator: adding sound to the notification");

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    final Notification notification;
    // This sets the text for the collapsed form:
    noti.setContentText(info.formatBigMessage(context));

    if (info.mAttachmentBitmap != null) {
        // The message has a picture, show that

        notification = new Notification.BigPictureStyle(noti).bigPicture(info.mAttachmentBitmap)
                // This sets the text for the expanded picture form:
                .setSummaryText(info.formatPictureMessage(context)).build();
    } else {
        // Show a single notification -- big style with the text of the whole message
        notification = new Notification.BigTextStyle(noti).bigText(info.formatBigMessage(context)).build();
    }

    notifyUserIfFullScreen(context, title);
    nm.notify(ICC_NOTIFICATION_ID_BASE + subId, notification);
}

From source file:com.amaze.filemanager.services.CopyService.java

void generateNotification(ArrayList<HFile> failedOps, boolean move) {
    if (failedOps.size() == 0)
        return;/*from   www.  ja  v  a  2  s .  com*/
    mNotifyManager.cancelAll();
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(c);
    mBuilder.setContentTitle("Operation Unsuccessful");
    mBuilder.setContentText("Some files weren't %s successfully".replace("%s", move ? "moved" : "copied"));
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("failedOps", failedOps);
    intent.putExtra("move", move);
    PendingIntent pIntent = PendingIntent.getActivity(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pIntent);
    mBuilder.setSmallIcon(R.drawable.ic_content_copy_white_36dp);
    mNotifyManager.notify(741, mBuilder.build());
    intent = new Intent("general_communications");
    intent.putExtra("failedOps", failedOps);
    intent.putExtra("move", move);
    sendBroadcast(intent);
}

From source file:com.heightechllc.breakify.MainActivity.java

/**
 * Starts the work or break timer//from   ww  w  .java 2 s. c  om
 * @param duration The number of milliseconds to run the timer for. If currently paused, this
 *                 is the remaining time.
 */
@TargetApi(19)
private void startTimer(long duration) {
    // Stop blinking the time and state labels
    timeLbl.clearAnimation();
    stateLbl.clearAnimation();

    // Show the "Reset" and "Skip" btns
    resetBtn.setVisibility(View.VISIBLE);
    skipBtn.setVisibility(View.VISIBLE);

    // Update the start / stop label
    startStopLbl.setText(R.string.stop);
    startStopLbl.setVisibility(View.VISIBLE);

    if (timerState == TIMER_STATE_PAUSED && circleTimer.getTotalTime() > 0) {
        // We're resuming from a paused state, so calculate how much time is remaining, based
        //  on the total time set in the circleTimer
        circleTimer.setPassedTime(circleTimer.getTotalTime() - duration, false);
    } else {
        circleTimer.setTotalTime(duration);
        circleTimer.setPassedTime(0, false);
        circleTimer.updateTimeLbl(duration);
        // Record the total duration, so we can resume if the activity is destroyed
        sharedPref.edit().putLong("schedTotalTime", duration).apply();
    }

    circleTimer.startIntervalAnimation();

    timerState = TIMER_STATE_RUNNING;

    // Schedule the alarm to go off
    PendingIntent pi = PendingIntent.getBroadcast(this, ALARM_MANAGER_REQUEST_CODE,
            new Intent(this, AlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
    long ringTime = SystemClock.elapsedRealtime() + duration;
    if (Build.VERSION.SDK_INT >= 19) {
        // API 19 needs setExact()
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, ringTime, pi);
    } else {
        // APIs 1-18 use set()
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, ringTime, pi);
    }
    // Show the persistent notification
    AlarmNotifications.showUpcomingNotification(this, ringTime, getWorkState());

    // Record when the timer will ring and remove record of time remaining for the paused timer.
    // Save the scheduled ring time using Unix / epoch time, not elapsedRealtime, b/c that is
    //  reset on each boot.
    long timeFromNow = ringTime - SystemClock.elapsedRealtime();
    long ringUnixTime = System.currentTimeMillis() + timeFromNow;
    sharedPref.edit().putLong("schedRingTime", ringUnixTime).remove("pausedTimeRemaining").apply();
}

From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java

private void mute(int alarmId) {
    Log.d(TAG, "mute()");

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_WAITING) {
        Log.d(TAG, "mute() blocked - waiting for a location update");
        return;/*  www  .  java  2  s  .  c  o m*/
    }

    // check if phone is already muted by the user
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    boolean isPhoneAlreadyMuted = audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL
            && !Preferences.isMutingPeriod(preferences);
    if (isPhoneAlreadyMuted) {
        Log.d(TAG, "phone is already muted, scheduling next mute");
        scheduleMute(true);
        return;
    }

    // load the current period from the db
    MutingPeriod mutingPeriod = null;
    Log.d(TAG, "muting period id: " + alarmId);
    if (DEBUG_WITH_FAKE_ALARMS) {
        mutingPeriod = new MutingPeriod();
        mutingPeriod.setId(-1);
        mutingPeriod.setBegin(System.currentTimeMillis());
        mutingPeriod.setEnd(mutingPeriod.getBegin() + 10000);
        mutingPeriod.setName("Fakeevent");
    } else {
        mutingPeriod = Studentportal.getStudentPortalDB().mutingPeriods_getPeriod(alarmId);
    }

    // check if phone is located at university
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_started_locating));
    boolean isPhoneLocationKnown = false;
    boolean isPhoneLocatedAtUniversity = false;
    String locationSource = null;

    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        ScanResult scanResult = MutingUtils.findMutingWifiNetwork(wifiManager.getScanResults());
        if (scanResult != null) {
            Log.d(TAG, "phone located by wifi: " + scanResult.SSID);
            isPhoneLocationKnown = true;
            isPhoneLocatedAtUniversity = true;
            locationSource = "wifi (" + scanResult.SSID + ")";
        }
    }

    if (!isPhoneLocationKnown) {
        // phone location could not be determined by wifi, trying network location instead...
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            Intent locationIntent = new Intent("at.ac.uniklu.mobile.sportal.LOCATION_UPDATE")
                    .putExtra(EXTRA_ALARM_ID, alarmId);
            PendingIntent pendingLocationIntent = PendingIntent.getBroadcast(this, 0, locationIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // remove the location receiver (so it doesn't get registered multiple times [could also happen on overlapping mute() calls)
            locationManager.removeUpdates(pendingLocationIntent);

            if (Preferences.getLocationStatus(preferences) == Preferences.LOCATION_STATUS_RECEIVED) {
                isPhoneLocationKnown = true;
                pendingLocationIntent.cancel();
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                if (location == null) {
                    Log.d(TAG, "location received but still null");
                } else {
                    MutingRegion mutingRegion = MutingUtils.findOverlappingMutingRegion(location);
                    if (mutingRegion != null) {
                        Log.d(TAG, "phone located by network @ " + mutingRegion.getName());
                        isPhoneLocatedAtUniversity = true;
                        locationSource = "location (" + mutingRegion.getName() + ")";
                    }
                }
            } else {
                Log.d(TAG, "trying to locate the phone by network...");
                // wait for a location update
                Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_WAITING);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                        pendingLocationIntent);
                return; // exit method - it will be re-called from the location broadcast receiver on a location update
            }
        }
    }

    boolean isAlwaysMuteEnabled = Preferences.isAutomuteWithoutLocation(this, preferences);

    if (isPhoneLocationKnown) {
        if (!isPhoneLocatedAtUniversity) {
            Log.d(TAG, "phone is not located at university, scheduling next mute");
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    } else {
        Log.d(TAG, "phone cannot be located");
        if (!isAlwaysMuteEnabled) {
            Log.d(TAG, "alwaysmute is disabled, scheduling next mute");
            Preferences.setLocationStatus(preferences, Preferences.LOCATION_STATUS_NONE);
            scheduleMute(true);
            removeNotification(Studentportal.NOTIFICATION_MS_INFO);
            return;
        }
    }

    // only turn the ringtone off if we aren't currently in a muting period.
    // if we are in a muting period the ringtone is already muted and the request should be ignored,
    // else rintoneTurnOn() won't turn the ringtone back on because ringtone override will be set to true
    if (!Preferences.isMutingPeriod(preferences)) {
        MutingUtils.ringtoneTurnOff(this);
    }

    // persist that from now on the phone is in a muting period
    Preferences.setMutingPeriod(preferences, true);

    // inform user via a notification that a course has started and the phone has been muted
    notifyUser(Studentportal.NOTIFICATION_MS_INFO, true, mutingPeriod.getName(), mutingPeriod.getName(),
            getString(R.string.automute_notification_course_muted));

    final boolean isPhoneLocationKnownAnalytics = isPhoneLocationKnown;
    final String locationSourceAnalytics = locationSource;
    Analytics.onEvent(Analytics.EVENT_MUTINGSERVICE_MUTE, "isPhoneLocationKnown",
            isPhoneLocationKnownAnalytics + "", "locationSource", locationSourceAnalytics);

    scheduleUnmute(mutingPeriod.getEnd());
}

From source file:com.android.development.Connectivity.java

private void scheduleAlarm(long delayMs, String eventType) {
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(CONNECTIVITY_TEST_ALARM);

    i.putExtra(TEST_ALARM_EXTRA, eventType);
    i.putExtra(TEST_ALARM_ON_EXTRA, Long.toString(mSCOnDuration));
    i.putExtra(TEST_ALARM_OFF_EXTRA, Long.toString(mSCOffDuration));
    i.putExtra(TEST_ALARM_CYCLE_EXTRA, Integer.toString(mSCCycleCount));

    PendingIntent p = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayMs, p);
}

From source file:be.ugent.zeus.hydra.util.audiostream.MusicService.java

/**
 * Updates the notification.//  w ww.  ja  v a 2 s.c om
 */
void updateNotification(String text) {
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
            new Intent(getApplicationContext(), Urgent.class), PendingIntent.FLAG_UPDATE_CURRENT);
    mNotification.setLatestEventInfo(getApplicationContext(), "Urgent.fm", text, pi);
    mNotificationManager.notify(NOTIFICATION_ID, mNotification);
}

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

static synchronized void showAlarmNotification(Service service, AlarmInstance instance) {
    LogUtils.v("Displaying alarm notification for alarm instance: " + instance.mId);

    Resources resources = service.getResources();
    NotificationCompat.Builder notification = new NotificationCompat.Builder(service)
            .setContentTitle(instance.getLabelOrDefault(service))
            .setContentText(AlarmUtils.getFormattedTime(service, instance.getAlarmTime()))
            .setColor(ContextCompat.getColor(service, com.androidinspain.deskclock.R.color.default_background))
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm).setOngoing(true)
            .setAutoCancel(false).setDefaults(NotificationCompat.DEFAULT_LIGHTS).setWhen(0)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setLocalOnly(true);/*from w  w w .jav  a 2 s  . co m*/

    // Setup Snooze Action
    Intent snoozeIntent = AlarmStateManager.createStateChangeIntent(service, AlarmStateManager.ALARM_SNOOZE_TAG,
            instance, AlarmInstance.SNOOZE_STATE);
    snoozeIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent snoozePendingIntent = PendingIntent.getService(service, ALARM_FIRING_NOTIFICATION_ID,
            snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(com.androidinspain.deskclock.R.drawable.ic_snooze_24dp,
            resources.getString(com.androidinspain.deskclock.R.string.alarm_alert_snooze_text),
            snoozePendingIntent);

    // Setup Dismiss Action
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(service,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    dismissIntent.putExtra(AlarmStateManager.FROM_NOTIFICATION_EXTRA, true);
    PendingIntent dismissPendingIntent = PendingIntent.getService(service, ALARM_FIRING_NOTIFICATION_ID,
            dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.addAction(com.androidinspain.deskclock.R.drawable.ic_alarm_off_24dp,
            resources.getString(com.androidinspain.deskclock.R.string.alarm_alert_dismiss_text),
            dismissPendingIntent);

    // Setup Content Action
    Intent contentIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);
    notification.setContentIntent(PendingIntent.getActivity(service, ALARM_FIRING_NOTIFICATION_ID,
            contentIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup fullscreen intent
    Intent fullScreenIntent = AlarmInstance.createIntent(service, AlarmActivity.class, instance.mId);
    // set action, so we can be different then content pending intent
    fullScreenIntent.setAction("fullscreen_activity");
    fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    notification.setFullScreenIntent(PendingIntent.getActivity(service, ALARM_FIRING_NOTIFICATION_ID,
            fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT), true);
    notification.setPriority(NotificationCompat.PRIORITY_MAX);

    clearNotification(service, instance);
    service.startForeground(ALARM_FIRING_NOTIFICATION_ID, notification.build());
}

From source file:br.com.bioscada.apps.biotracks.widgets.TrackWidgetProvider.java

/**
 * Updates the record button./*from  w ww  .  j  a  v a  2 s .  c o m*/
 * 
 * @param context the context
 * @param remoteViews the remote views
 * @param isRecording true if recording
 * @param recordingTrackPaused true if recording track is paused
 */
private static void updateRecordButton(Context context, RemoteViews remoteViews, boolean isRecording,
        boolean recordingTrackPaused) {
    remoteViews.setImageViewResource(R.id.track_widget_record_button,
            isRecording && !recordingTrackPaused ? R.drawable.button_pause : R.drawable.button_record);
    int recordActionId;
    if (isRecording) {
        recordActionId = recordingTrackPaused ? R.string.track_action_resume : R.string.track_action_pause;
    } else {
        recordActionId = R.string.track_action_start;
    }
    Intent intent = new Intent(context, ControlRecordingService.class)
            .setAction(context.getString(recordActionId));
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setOnClickPendingIntent(R.id.track_widget_record_button, pendingIntent);
}