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:at.vcity.androidimsocket.services.IMService.java

public void authenticationResult(Object... args) {
    this.authenticatedUser = true;
    try {/* w  ww.  jav  a2  s.c  o m*/
        JSONObject param = new JSONObject(args[0].toString());
        String result = param.getString("result");
        if (result.equals(NetworkCommand.SUCCESSFUL)) {
            //currentUserId=param.getString("userId");
            FriendInfo f = new FriendInfo();
            f.userName = username;
            f.userId = param.getString("userId");
            Chatting.setCurrentUser(f);

            // getFriendList();

            AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, IMService.class);
            intent.putExtra("myToken", socketOperator.getToken());
            intent.putExtra("username", username);
            intent.putExtra("password", password);
            PendingIntent pintent = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                    SystemClock.elapsedRealtime() + WAKE_TIME_PERIOD, WAKE_TIME_PERIOD, pintent);

            Intent loginintent = new Intent(TRY_LOGIN);
            loginintent.putExtra("AUTHENTICATION_RESULT", NetworkCommand.SUCCESSFUL);
            sendBroadcast(loginintent);

            // Start heartbeat
            heartIsBeating = true;
            startHeartbeat();
        } else {
            Toast.makeText(this, "Wrong user name", Toast.LENGTH_SHORT).show();
        }
    } catch (JSONException e) {
    }
    ;
}

From source file:com.parse.ParsePushBroadcastReceiver.java

/**
 * Creates a {@link Notification} with reasonable defaults. If "alert" and "title" are
 * both missing from data, then returns {@code null}. If the text in the notification is longer
 * than 38 characters long, the style of the notification will be set to
 * {@link android.app.Notification.BigTextStyle}.
 * <p/>/*from  w w  w . j a  v  a2s . c  o m*/
 * As a security precaution, developers overriding this method should be sure to set the package
 * on notification {@code Intent}s to avoid leaking information to other apps.
 *
 * @param context
 *      The {@code Context} in which the receiver is running.
 * @param intent
 *      An {@code Intent} containing the channel and data of the current push notification.
 * @return
 *      The notification to be displayed.
 *
 * @see ParsePushBroadcastReceiver#onPushReceive(Context, Intent)
 */
protected Notification getNotification(Context context, Intent intent) {
    JSONObject pushData = getPushData(intent);
    if (pushData == null || (!pushData.has("alert") && !pushData.has("title"))) {
        return null;
    }

    String title = pushData.optString("title", ManifestInfo.getDisplayName(context));
    String alert = pushData.optString("alert", "Notification received.");
    String tickerText = String.format(Locale.getDefault(), "%s: %s", title, alert);

    Bundle extras = intent.getExtras();

    Random random = new Random();
    int contentIntentRequestCode = random.nextInt();
    int deleteIntentRequestCode = random.nextInt();

    // Security consideration: To protect the app from tampering, we require that intent filters
    // not be exported. To protect the app from information leaks, we restrict the packages which
    // may intercept the push intents.
    String packageName = context.getPackageName();

    Intent contentIntent = new Intent(ParsePushBroadcastReceiver.ACTION_PUSH_OPEN);
    contentIntent.putExtras(extras);
    contentIntent.setPackage(packageName);

    Intent deleteIntent = new Intent(ParsePushBroadcastReceiver.ACTION_PUSH_DELETE);
    deleteIntent.putExtras(extras);
    deleteIntent.setPackage(packageName);

    PendingIntent pContentIntent = PendingIntent.getBroadcast(context, contentIntentRequestCode, contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pDeleteIntent = PendingIntent.getBroadcast(context, deleteIntentRequestCode, deleteIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The purpose of setDefaults(Notification.DEFAULT_ALL) is to inherit notification properties
    // from system defaults
    NotificationCompat.Builder parseBuilder = new NotificationCompat.Builder(context);
    parseBuilder.setContentTitle(title).setContentText(alert).setTicker(tickerText)
            .setSmallIcon(this.getSmallIconId(context, intent)).setLargeIcon(this.getLargeIcon(context, intent))
            .setContentIntent(pContentIntent).setDeleteIntent(pDeleteIntent).setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL);
    if (alert != null && alert.length() > ParsePushBroadcastReceiver.SMALL_NOTIFICATION_MAX_CHARACTER_LIMIT) {
        parseBuilder.setStyle(new NotificationCompat.Builder.BigTextStyle().bigText(alert));
    }
    return parseBuilder.build();
}

From source file:br.com.bioscada.apps.biotracks.services.TrackRecordingService.java

@Override
public void onCreate() {
    super.onCreate();
    executorService = Executors.newSingleThreadExecutor();
    context = this;
    myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this);
    handler = new Handler();
    myTracksLocationManager = new MyTracksLocationManager(this, handler.getLooper(), true);
    activityRecognitionPendingIntent = PendingIntent.getService(context, 0,
            new Intent(context, ActivityRecognitionIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
    activityRecognitionClient = new ActivityRecognitionClient(context, activityRecognitionCallbacks,
            activityRecognitionFailedListener);
    try {//from  w  w  w. j  av  a  2s . c  o  m
        activityRecognitionClient.connect();
    } catch (Exception e) {
        Log.d("BIOTRACKS", e.getMessage());
    }

    splitExecutor = new PeriodicTaskExecutor(this, new SplitPeriodicTaskFactory());
    voiceSplitExecutor = new PeriodicTaskExecutor(this, new AnnouncementPeriodicTaskFactory());
    voice1Executor = new PeriodicTaskExecutor(this, new AnnouncementPeriodicTaskFactory());
    voice2Executor = new PeriodicTaskExecutor(this, new AnnouncementPeriodicTaskFactory());
    sharedPreferences = getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
    sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);

    // onSharedPreferenceChanged might not set recordingTrackId.
    recordingTrackId = PreferencesUtils.RECORDING_TRACK_ID_DEFAULT;

    // Require voiceExecutor and splitExecutor to be created.
    sharedPreferenceChangeListener.onSharedPreferenceChanged(sharedPreferences, null);

    handler.post(registerLocationRunnable);

    /*
     * Try to restart the previous recording track in case the service has been
     * restarted by the system, which can sometimes happen.
     */
    Track track = myTracksProviderUtils.getTrack(recordingTrackId);
    if (track != null) {
        restartTrack(track);
    } else {
        if (isRecording()) {
            Log.w(TAG, "track is null, but recordingTrackId not -1L. " + recordingTrackId);
            updateRecordingState(PreferencesUtils.RECORDING_TRACK_ID_DEFAULT, true);
        }
        showNotification(false);
    }
}

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

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

    String label = instance.mLabel;
    String alarmTime = AlarmUtils.getFormattedTime(context, instance.getAlarmTime());
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setShowWhen(false)
            .setContentTitle(context.getString(com.androidinspain.deskclock.R.string.alarm_missed_title))
            .setContentText(instance.mLabel.isEmpty() ? alarmTime
                    : context.getString(com.androidinspain.deskclock.R.string.alarm_missed_text, alarmTime,
                            label))//from  w  w w.  j  a  v  a2s .c  o m
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background))
            .setSortKey(createSortKey(instance))
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_alarm)
            .setPriority(NotificationCompat.PRIORITY_HIGH).setCategory(NotificationCompat.CATEGORY_ALARM)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setLocalOnly(true);

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

    final int id = instance.hashCode();

    // Setup dismiss intent
    Intent dismissIntent = AlarmStateManager.createStateChangeIntent(context,
            AlarmStateManager.ALARM_DISMISS_TAG, instance, AlarmInstance.DISMISSED_STATE);
    builder.setDeleteIntent(
            PendingIntent.getService(context, id, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    // Setup content intent
    Intent showAndDismiss = AlarmInstance.createIntent(context, AlarmStateManager.class, instance.mId);
    showAndDismiss.putExtra(EXTRA_NOTIFICATION_ID, id);
    showAndDismiss.setAction(AlarmStateManager.SHOW_AND_DISMISS_ALARM_ACTION);
    builder.setContentIntent(
            PendingIntent.getBroadcast(context, id, showAndDismiss, PendingIntent.FLAG_UPDATE_CURRENT));

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

From source file:edu.mit.media.funf.probe.Probe.java

private void updateInternalRequestsPendingIntent() {
    PendingIntent internalPendingIntent = PendingIntent.getService(this, 0, requestsIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    // Keep the pending intent valid, by having the alarm clock keep a reference to it
    AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
    manager.set(AlarmManager.RTC, System.currentTimeMillis() + FAR_IN_FUTURE_MILLIS, internalPendingIntent);
}

From source file:com.aero2.android.DefaultActivities.SmogMapActivity.java

public void notifyServiceComplete() {
    //Set the boolean in cache to state true i.e. the service is complete.
    SharedPreferences afterServiceCompletion = getApplicationContext()
            .getSharedPreferences("AFTER_SERVICE_COMPLETED", Context.MODE_WORLD_WRITEABLE);
    SharedPreferences.Editor afterServiceCompletionEditor = afterServiceCompletion.edit();
    afterServiceCompletionEditor.putBoolean("AFTER_SERVICE_COMPLETED", true);
    afterServiceCompletionEditor.commit();

    //Notify the User that the download service has been completed
    int mNotificationId = 235;
    NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Data AerO2")
            .setContentText("Smog Data Download Complete");
    NotificationManager mNotifyMgr = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE);
    Intent resultIntent = new Intent(this, SmogMapActivity.class);

    //What to do if the notification is clicked??
    PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    mNotifyMgr.notify(mNotificationId, mBuilder.build());

    /*//w  ww  .ja v a  2s.  c  om
     Once the service is complete notify the system that service isn't
     completed so that it doesn't refresh the activity over and over again.
     sorry this might seen a bit wiered but this is how it works.
    */
    SharedPreferences serviceStatus = getApplicationContext().getSharedPreferences("SERVICE_COMPLETED",
            Context.MODE_WORLD_WRITEABLE);
    SharedPreferences.Editor serviceStatusEdit = serviceStatus.edit();
    serviceStatusEdit.putBoolean("SERVICE_COMPLETED", false);
    serviceStatusEdit.commit();

}

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

private static void generateNotification(Noticia noticia, 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("Nova noticia");
    mBuilder.setContentText(noticia.getAssunto());
    mBuilder.setTicker("Noticia !!!");
    mBuilder.setSmallIcon(R.drawable.logo);

    /* Increase notification number every time a new notification arrives */
    mBuilder.setNumber(++numMessages);//w  w w.  j a v  a 2 s . co m

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

    resultIntent.setAction("NOTICIA"); //tentando linkar
    Bundle bundle = new Bundle();
    bundle.putSerializable("noticia", noticia);
    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);
            //                (NotificationManager) getContext().getSystemService(getContext().NOTIFICATION_SERVICE);
            //                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    /* notificationID allows you to update the notification later on. */
    mNotificationManager.notify(noticia.getCodigo(), mBuilder.build());
}

From source file:com.androidinspain.deskclock.data.TimerNotificationBuilder.java

Notification buildMissed(Context context, NotificationModel nm, List<Timer> missedTimers) {
    final Timer timer = missedTimers.get(0);
    final int count = missedTimers.size();

    // Compute some values required below.
    final long base = getChronometerBase(timer);
    final String pname = context.getPackageName();
    final Resources res = context.getResources();

    final Action action;

    final CharSequence stateText;
    if (count == 1) {
        // Single timer is missed.
        if (TextUtils.isEmpty(timer.getLabel())) {
            stateText = res.getString(com.androidinspain.deskclock.R.string.missed_timer_notification_label);
        } else {/*from  ww w.jav a  2s  .com*/
            stateText = res.getString(
                    com.androidinspain.deskclock.R.string.missed_named_timer_notification_label,
                    timer.getLabel());
        }

        // Reset button
        final Intent reset = new Intent(context, TimerService.class).setAction(TimerService.ACTION_RESET_TIMER)
                .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId());

        @DrawableRes
        final int icon1 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
        final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_reset);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset);
        action = new Action.Builder(icon1, title1, intent1).build();
    } else {
        // Multiple missed timers.
        stateText = res.getString(com.androidinspain.deskclock.R.string.timer_multi_missed, count);

        final Intent reset = TimerService.createResetMissedTimersIntent(context);

        @DrawableRes
        final int icon1 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
        final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.timer_reset_all);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset);
        action = new Action.Builder(icon1, title1, intent1).build();
    }

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, TimerService.class).setAction(TimerService.ACTION_SHOW_TIMER)
            .putExtra(TimerService.EXTRA_TIMER_ID, timer.getId())
            .putExtra(Events.EXTRA_EVENT_LABEL, com.androidinspain.deskclock.R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getService(context, REQUEST_CODE_MISSING, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    final Builder notification = new NotificationCompat.Builder(context).setLocalOnly(true).setShowWhen(false)
            .setAutoCancel(false).setContentIntent(pendingShowApp).setPriority(Notification.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM)
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_timer)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setSortKey(nm.getTimerNotificationMissedSortKey())
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle()).addAction(action)
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background));

    if (Utils.isNOrLater()) {
        notification.setCustomContentView(buildChronometer(pname, base, true, stateText))
                .setGroup(nm.getTimerNotificationGroupKey());
    } else {
        final CharSequence contentText = AlarmUtils.getFormattedTime(context,
                timer.getWallClockExpirationTime());
        notification.setContentText(contentText).setContentTitle(stateText);
    }

    return notification.build();
}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

@Override
public void onClick(View view) {
    int id = view.getId();
    ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
    switch (id) {
    case R.id.chat_send:

        smiliesShell.setVisibility(View.GONE);
        EditText message = (EditText) findViewById(R.id.chat_text);
        String messageT = message.getText().toString();
        if (messageT.length() == 0) {
            Toast.makeText(this, R.string.no_message, Toast.LENGTH_SHORT).show();
            return;
        }/*from w  w  w  .j  a  va2  s .com*/
        if (messageT.length() > 140) {
            Toast.makeText(this, R.string.message_too_long, Toast.LENGTH_SHORT).show();
            return;
        }
        nvp.add(new BasicNameValuePair("message", messageT));
        doSubmit("chatform", nvp, true);
        doChatScroll = true;
        break;
    case R.id.med_send:
        int w = walkingPicker.getValue();
        int s = sittingPicker.getValue();

        if (w == 0 && s == 0) {
            Toast.makeText(this, R.string.no_time, Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("walking", w);
        editor.putInt("sitting", s);
        editor.apply();

        lastWalking = w * 5;
        lastSitting = s * 5;

        startMeditating = true;

        nvp.add(new BasicNameValuePair("walking", lastWalking + ""));
        nvp.add(new BasicNameValuePair("sitting", lastSitting + ""));
        doSubmit("timeform", nvp, true);
        break;
    case R.id.med_cancel:

        Intent rIntent = new Intent(this, ReceiverAlarm.class);
        PendingIntent walkPendingIntent = PendingIntent.getBroadcast(context, 0, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent sitPendingIntent = PendingIntent.getBroadcast(context, 1, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        mAlarmMgr.cancel(walkPendingIntent);
        mAlarmMgr.cancel(sitPendingIntent);
        mNM.cancelAll();

        doSubmit("cancelform", nvp, true);
        break;
    case R.id.smily_button:
        if (smiliesShell.getVisibility() == View.GONE)
            smiliesShell.setVisibility(View.VISIBLE);
        else
            smiliesShell.setVisibility(View.GONE);
        break;
    case R.id.chat_text:
        smiliesShell.setVisibility(View.GONE);
        singleClick++;
        Handler handler = new Handler();
        Runnable r = new Runnable() {

            @Override
            public void run() {
                singleClick = 0;
            }
        };

        if (singleClick == 1) {
            //Single click
            handler.postDelayed(r, 250);
        } else if (singleClick == 2) {
            //Double click
            singleClick = 0;
            ((EditText) findViewById(R.id.chat_text)).setText("");
        }
        break;
    case R.id.new_commit:
        Intent i = new Intent(this, ActivityCommit.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        break;
    default:
        smiliesShell.setVisibility(View.GONE);
        break;
    }
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private void onProbeFinish() {
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent i = new Intent(CensorCensusService.this, CensorCensusService.class);
    i.putExtra(API.EXTRA_POLL, true);//from   w  ww.j av  a 2  s. c  om
    PendingIntent pi = PendingIntent.getService(CensorCensusService.this, 0, i,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //If we are polling lets set our next tick
    if (getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE)
            .getInt(API.SETTINGS_GCM_PREFERENCE, API.SETTINGS_GCM_FULL) == API.SETTINGS_GCM_DISABLED) {
        am.cancel(pi); // cancel any existing alarms
        //TODO Setback to 60000
        long repeat = (long) (getPreferences(CensorCensusService.this).getInt(API.SETTINGS_FREQUENCY, 1)
                * 60000);//60000 or 5000
        Log.e("onProbeFinish", Long.toString(repeat));
        Log.e("onProbeFinish", "          -         ");
        Log.e("onProbeFinish", "          -         ");
        Log.e("onProbeFinish", "          -         ");
        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + repeat, pi);
    } else {
        Log.e("onProbeFinish", "Cancel everything!");
        Log.e("onProbeFinish", "          -         ");
        Log.e("onProbeFinish", "          -         ");
        Log.e("onProbeFinish", "          -         ");
        am.cancel(pi); // cancel any existing alarms
        stopSelf();
    }
}