Example usage for android.app PendingIntent FLAG_ONE_SHOT

List of usage examples for android.app PendingIntent FLAG_ONE_SHOT

Introduction

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

Prototype

int FLAG_ONE_SHOT

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

Click Source Link

Document

Flag indicating that this PendingIntent can be used only once.

Usage

From source file:fr.kwiatkowski.apktrack.service.WebService.java

/**
 * This method is called when a MessageModifiedEvent is posted on the event bus, but the
 * activity is not around to catch it./*from w w  w  .j  av a  2s . co  m*/
 *
 * A notification is displayed to the user since the UI cannot be updated.
 *
 * @param ignored Never used.
 */
public void onEvent(StickyUpdatedMessage ignored) {
    ModelModifiedMessage m = EventBus.getDefault().getStickyEvent(ModelModifiedMessage.class);
    List<InstalledApp> updated_apps = new ArrayList<InstalledApp>();
    List<Pair<ModelModifiedMessage.event_type, String>> events = m.access_events(new MessageAccessor());
    if (events.size() == 0) {
        return;
    }

    // Check the last event posted. It may not require a notification to be trigerred.
    Pair<ModelModifiedMessage.event_type, String> last = events.get(events.size() - 1);
    if (last.first != ModelModifiedMessage.event_type.APP_UPDATED) {
        return;
    }
    InstalledApp app = InstalledApp.find_app(last.second);
    if (app == null || !app.is_update_available() || app.has_notified()) {
        return;
    }

    // Build the list of apps which will be mentioned in the notification.
    for (Pair<ModelModifiedMessage.event_type, String> p : events) {
        if (p.first != ModelModifiedMessage.event_type.APP_UPDATED) {
            continue;
        }
        app = InstalledApp.find_app(p.second);
        if (app == null || !app.is_update_available() || app.has_notified()) {
            continue;
        }

        if (!updated_apps.contains(app)) {
            updated_apps.add(app);
        }
    }

    if (updated_apps.size() == 0) {
        return;
    }

    Resources r = getResources();
    NotificationCompat.Builder b = new NotificationCompat.Builder(this);
    // Show a notification for updated apps
    if (updated_apps.size() == 1) {
        app = updated_apps.get(updated_apps.size() - 1);
        b.setContentTitle(r.getString(R.string.app_updated_notification, app.get_display_name()))
                .setContentText(r.getString(R.string.app_version_available, app.get_latest_version()))
                .setTicker(r.getString(R.string.app_can_be_updated, app.get_display_name()))
                .setSmallIcon(R.drawable.ic_menu_refresh).setAutoCancel(true); //TODO: Think about launching the search/download on user click.
    } else {
        b.setContentTitle(r.getString(R.string.apps_updated_notification))
                .setContentText(r.getString(R.string.apps_updated_notification_summary,
                        updated_apps.get(updated_apps.size() - 1).get_display_name(), updated_apps.size() - 1))
                .setTicker(r.getString(R.string.apps_updated_notification))
                .setSmallIcon(R.drawable.ic_menu_refresh).setAutoCancel(true);

        NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
        for (InstalledApp ia : updated_apps) {
            style.addLine(r.getString(R.string.app_version_available_2, ia.get_display_name(), ia.get_version(),
                    ia.get_latest_version()));
        }
        style.setBigContentTitle(r.getString(R.string.apps_updated_notification));
        b.setStyle(style);
    }

    // Open ApkTrack when the notification is clicked.
    Intent i = new Intent();
    i.setClass(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_ONE_SHOT);
    b.setContentIntent(pi);

    NotificationManager mgr = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
    mgr.notify(1, b.build()); // Consolidate notifications.
}

From source file:com.cerema.cloud2.syncadapter.FileSyncAdapter.java

/**
 * Notifies the user about a failed synchronization through the status notification bar 
 *///from w  ww  .  jav a 2 s  .c o  m
private void notifyFailedSynchronization() {
    NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
    boolean needsToUpdateCredentials = (mLastFailedResult != null
            && (mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED
                    || mLastFailedResult.isIdPRedirection()));
    if (needsToUpdateCredentials) {
        // let the user update credentials with one click
        Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
                AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
        notificationBuilder.setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
                .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
                .setContentIntent(PendingIntent.getActivity(getContext(), (int) System.currentTimeMillis(),
                        updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT))
                .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
    } else {
        notificationBuilder.setTicker(i18n(R.string.sync_fail_ticker))
                .setContentTitle(i18n(R.string.sync_fail_ticker))
                .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
    }

    showNotification(R.string.sync_fail_ticker, notificationBuilder);
}

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 {/*  w  ww.ja  v  a 2 s.  c  o m*/
            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:com.facebook.notifications.NotificationsManager.java

/**
 * Present a {@link Notification} to be presented from a GCM push bundle.
 * <p/>//from  w w  w.j a v a 2s .c o  m
 * This does not present a notification immediately, instead it caches the assets from the
 * notification bundle, and then presents a notification to the user. This allows for a smoother
 * interaction without loading indicators for the user.
 * <p/>
 * Note that only one notification can be created for a specific push bundle, should you attempt
 * to present a new notification with the same payload bundle as an existing notification, it will
 * replace and update the old notification.
 *
 * @param context              The context to send the notification from
 * @param notificationBundle   The content of the push notification
 * @param launcherIntent       The launcher intent that contains your Application's activity.
 *                             This will be modified with the FLAG_ACTIVITY_CLEAR_TOP and
 *                             FLAG_ACTIVITY_SINGLE_TOP flags, in order to properly show the
 *                             notification in an already running application.
 *                             <p/>
 *                             Should you not want this behavior, you may use the notificationExtender
 *                             parameter to customize the contentIntent of the notification before
 *                             presenting it.
 * @param notificationExtender A nullable argument that allows you to customize the notification
 *                             before displaying it. Use this to configure Icons, text, sounds,
 *                             etc. before we pass the notification off to the OS.
 */
public static boolean presentNotification(@NonNull final Context context,
        @NonNull final Bundle notificationBundle, @NonNull final Intent launcherIntent,
        @Nullable final NotificationExtender notificationExtender) {
    final JSONObject alert;
    final int payloadHash;

    try {
        String payload = notificationBundle.getString(CARD_PAYLOAD_KEY);
        if (payload == null) {
            return false;
        }
        payloadHash = payload.hashCode();

        JSONObject payloadObject = new JSONObject(payload);
        alert = payloadObject.optJSONObject("alert") != null ? payloadObject.optJSONObject("alert")
                : new JSONObject();
    } catch (JSONException ex) {
        Log.e(LOG_TAG, "Error while parsing notification bundle JSON", ex);
        return false;
    }

    final boolean[] success = new boolean[1];

    final Thread backgroundThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            prepareCard(context, notificationBundle, new PrepareCallback() {
                @Override
                public void onPrepared(@NonNull Intent presentationIntent) {
                    Intent contentIntent = new Intent(launcherIntent);
                    contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    contentIntent.putExtra(EXTRA_PAYLOAD_INTENT, presentationIntent);

                    NotificationManager manager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification.Builder builder = new Notification.Builder(context)
                            .setSmallIcon(android.R.drawable.ic_dialog_alert)
                            .setContentTitle(alert.optString("title")).setContentText(alert.optString("body"))
                            .setAutoCancel(true)
                            .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(),
                                    payloadHash, contentIntent, PendingIntent.FLAG_ONE_SHOT));

                    if (notificationExtender != null) {
                        builder = notificationExtender.extendNotification(builder);
                    }

                    manager.notify(NOTIFICATION_TAG, payloadHash, builder.getNotification());
                    success[0] = true;
                    Looper.myLooper().quit();
                }

                @Override
                public void onError(@NonNull Exception exception) {
                    Log.e(LOG_TAG, "Error while preparing card", exception);
                    Looper.myLooper().quit();
                }
            });

            Looper.loop();
        }
    });

    backgroundThread.start();

    try {
        backgroundThread.join();
    } catch (InterruptedException ex) {
        Log.e(LOG_TAG, "Failed to wait for background thread", ex);
        return false;
    }
    return success[0];
}

From source file:es.ugr.swad.swadroid.modules.notifications.Notifications.java

@Override
protected void postConnect() {
    Notification notif;/*from   w  ww  .j  a v a 2 s . com*/
    Intent notificationIntent = new Intent(this, Notifications.class);
    PendingIntent pendingIntent;

    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //single top to avoid creating many activity stacks queue
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

    if (!SyncUtils.isSyncAutomatically(getApplicationContext())) {
        if (notifCount > 0) {
            notif = AlertNotificationFactory.createAlertNotification(getApplicationContext(),
                    getString(R.string.app_name), notifCount + " " + getString(R.string.notificationsAlertMsg),
                    getString(R.string.app_name), pendingIntent, R.drawable.ic_launcher_swadroid_notif,
                    R.drawable.ic_launcher_swadroid, true, true, false, false);

            AlertNotificationFactory.showAlertNotification(getApplicationContext(), notif, NOTIF_ALERT_ID);
        } else {
            Toast.makeText(this, R.string.NoNotificationsMsg, Toast.LENGTH_LONG).show();
        }

        // Sends to SWAD the "seen notifications" info
        sendReadedNotifications();

        refreshScreen();
    }
}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

public void startServerHearBeatAlarm() {
    if (heartBitIntent != null) {
        alarmManager.cancel(heartBitIntent);
        //return;
    }//from   w  w w  .ja  va2  s.c  om
    heartBitIntent = null;
    //serverHeartBit=60*1000;
    //if (!mDaemon.notUrgent) serverHeartBit=10*1000;
    Intent jIntent = new Intent(this, ConnectDaemonService.class);
    //M1-00 (cool) or M1-01 (warm)
    jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_BIT);
    heartBitIntent = PendingIntent.getService(this, ++heartBitRequestId % 100 + 1000, jIntent,
            PendingIntent.FLAG_ONE_SHOT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + serverHeartBit, heartBitIntent);
    Log.i("ALARM_SET", "restart new alarm set for " + serverHeartBit / 1000 + " seconds");
    //mDaemon.hasCommand=true;
    //mDaemon.interrupt();
}

From source file:com.android.deskclock.data.TimerModel.java

/**
 * Updates the callback given to this application from the {@link AlarmManager} that signals the
 * expiration of the next timer. If no timers are currently set to expire (i.e. no running
 * timers exist) then this method clears the expiration callback from AlarmManager.
 *///  w w  w  .  j  a  v a 2  s.c  o  m
private void updateAlarmManager() {
    // Locate the next firing timer if one exists.
    Timer nextExpiringTimer = null;
    for (Timer timer : getMutableTimers()) {
        if (timer.isRunning()) {
            if (nextExpiringTimer == null) {
                nextExpiringTimer = timer;
            } else if (timer.getExpirationTime() < nextExpiringTimer.getExpirationTime()) {
                nextExpiringTimer = timer;
            }
        }
    }

    // Build the intent that signals the timer expiration.
    final Intent intent = TimerService.createTimerExpiredIntent(mContext, nextExpiringTimer);

    if (nextExpiringTimer == null) {
        // Cancel the existing timer expiration callback.
        final PendingIntent pi = PendingIntent.getService(mContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE);
        if (pi != null) {
            mAlarmManager.cancel(pi);
            pi.cancel();
        }
    } else {
        // Update the existing timer expiration callback.
        final PendingIntent pi = PendingIntent.getService(mContext, 0, intent,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
        schedulePendingIntent(nextExpiringTimer.getExpirationTime(), pi);
    }
}

From source file:com.android.nfc.beam.BeamTransferManager.java

PendingIntent buildCancelIntent() {
    Intent intent = new Intent(BeamStatusReceiver.ACTION_CANCEL_HANDOVER_TRANSFER);
    intent.putExtra(BeamStatusReceiver.EXTRA_ADDRESS, mRemoteDevice.getAddress());
    intent.putExtra(BeamStatusReceiver.EXTRA_INCOMING,
            mIncoming ? BeamStatusReceiver.DIRECTION_INCOMING : BeamStatusReceiver.DIRECTION_OUTGOING);
    PendingIntent pi = PendingIntent.getBroadcast(mContext, mTransferId, intent, PendingIntent.FLAG_ONE_SHOT);

    return pi;/*from   w  w  w .j  av a 2s.  c o m*/
}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

void startOneBootAlarm() {
    if (oneBootIntent != null) {
        alarmManager.cancel(oneBootIntent);
        //return;
    }/* w  w  w .ja  va 2 s. co m*/
    oneBootIntent = null;
    String bootParameter = readBootParameter(1);
    Log.i("ALARM_SET", "got 1 boot parameters " + (bootParameter == null ? "nothing" : bootParameter));
    if (bootParameter == null)
        return;
    int idx = bootParameter.indexOf("-");
    if (idx < 0)
        return;
    long init_wait = Long.parseLong(bootParameter.substring(0, idx));
    if (init_wait < 10000) {
        long on_time = Long.parseLong(bootParameter.substring(idx + 1));
        sendCommand("M5-" + new DecimalFormat("00").format(on_time / 60000));
        return;
    }
    Intent jIntent = new Intent(this, ConnectDaemonService.class);
    //M1-00 (cool) or M1-01 (warm)
    jIntent.setAction(ALARM_1BOOT);
    jIntent.putExtra(ConnectDaemonService.ALARM_DONE, ALARM_1BOOT);
    jIntent.putExtra(ConnectDaemonService.ALARM_1BOOT, bootParameter.substring(idx + 1));
    oneBootIntent = PendingIntent.getService(this, ++boot1AlarmRequestId % 10 + 150, jIntent,
            PendingIntent.FLAG_ONE_SHOT);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + init_wait, oneBootIntent);
    Log.i("ALARM_SET", "to start one boot in " + init_wait / 60000);
    //startScheduledJobs();
}

From source file:com.digitalarx.android.files.services.FileDownloader.java

/**
 * Updates the status notification with the result of a download operation.
 * /*from  ww w  .  j a v a 2  s. c  om*/
 * @param downloadResult    Result of the download operation.
 * @param download          Finished download operation
 */
private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {
    mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
    if (!downloadResult.isCancelled()) {
        int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker
                : R.string.downloader_download_failed_ticker;

        boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED
                || downloadResult.isIdPRedirection());
        tickerId = (needsToUpdateCredentials) ? R.string.downloader_download_failed_credentials_error
                : tickerId;

        mNotificationBuilder.setTicker(getString(tickerId)).setContentTitle(getString(tickerId))
                .setAutoCancel(true).setOngoing(false).setProgress(0, 0, false);

        if (needsToUpdateCredentials) {

            // let the user update credentials with one click
            Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, download.getAccount());
            updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
                    AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
            mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this,
                    (int) System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));

            mDownloadClient = null; // grant that future retries on the same account will get the fresh credentials

        } else {
            // TODO put something smart in showDetailsIntent
            Intent showDetailsIntent = new Intent();
            mNotificationBuilder.setContentIntent(
                    PendingIntent.getActivity(this, (int) System.currentTimeMillis(), showDetailsIntent, 0));
        }

        mNotificationBuilder.setContentText(
                ErrorMessageAdapter.getErrorCauseMessage(downloadResult, download, getResources()));
        mNotificationManager.notify(tickerId, mNotificationBuilder.build());

        // Remove success notification
        if (downloadResult.isSuccess()) {
            // Sleep 2 seconds, so show the notification before remove it
            NotificationDelayer.cancelWithDelay(mNotificationManager,
                    R.string.downloader_download_succeeded_ticker, 2000);
        }

    }
}