Example usage for android.app PendingIntent FLAG_CANCEL_CURRENT

List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT

Introduction

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

Prototype

int FLAG_CANCEL_CURRENT

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

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

Usage

From source file:com.brq.wallet.lt.notification.GcmIntentService.java

private void showAdNotification(String type) {
    Intent intent;//from w ww  .j  a  v a2s .  com
    if (LtApi.AD_TIME_OUT_NOTIFICATION_TYPE.equals(type)) {
        intent = PinProtectedActivity.createIntent(this,
                LtMainActivity.createIntent(this, LtMainActivity.TAB_TYPE.MY_ADS));
    } else {
        // We don't know this type, so we ignore it
        return;
    }
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    String title = getResources().getString(R.string.lt_mycelium_local_trader_title);
    String message = getResources().getString(R.string.lt_ad_deactivating_message);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle(title)
            .setContentText(message).setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pIntent)
            .setAutoCancel(true);

    // Add ticker
    builder.setTicker(message);

    LocalTraderManager ltManager = MbwManager.getInstance(this).getLocalTraderManager();

    // Vibrate
    long[] pattern = { 500, 500 };
    builder.setVibrate(pattern);

    // Make a sound
    if (ltManager.getPlaySoundOnTradeNotification()) {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alarmSound != null) {
            builder.setSound(alarmSound);
        }
    }

    // Notify
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, builder.build());
}

From source file:at.bitfire.davdroid.syncadapter.SyncManager.java

@TargetApi(21)
public void performSync() {
    int syncPhase = SYNC_PHASE_PREPARE;
    try {/*www .j  a  v a 2 s . c  om*/
        App.log.info("Preparing synchronization");
        prepare();

        if (Thread.interrupted())
            return;
        syncPhase = SYNC_PHASE_QUERY_CAPABILITIES;
        App.log.info("Querying capabilities");
        queryCapabilities();

        syncPhase = SYNC_PHASE_PROCESS_LOCALLY_DELETED;
        App.log.info("Processing locally deleted entries");
        processLocallyDeleted();

        if (Thread.interrupted())
            return;
        syncPhase = SYNC_PHASE_PREPARE_DIRTY;
        App.log.info("Locally preparing dirty entries");
        prepareDirty();

        syncPhase = SYNC_PHASE_UPLOAD_DIRTY;
        App.log.info("Uploading dirty entries");
        uploadDirty();

        syncPhase = SYNC_PHASE_CHECK_SYNC_STATE;
        App.log.info("Checking sync state");
        if (checkSyncState()) {
            syncPhase = SYNC_PHASE_LIST_LOCAL;
            App.log.info("Listing local entries");
            listLocal();

            if (Thread.interrupted())
                return;
            syncPhase = SYNC_PHASE_LIST_REMOTE;
            App.log.info("Listing remote entries");
            listRemote();

            if (Thread.interrupted())
                return;
            syncPhase = SYNC_PHASE_COMPARE_LOCAL_REMOTE;
            App.log.info("Comparing local/remote entries");
            compareLocalRemote();

            syncPhase = SYNC_PHASE_DOWNLOAD_REMOTE;
            App.log.info("Downloading remote entries");
            downloadRemote();

            syncPhase = SYNC_PHASE_POST_PROCESSING;
            App.log.info("Post-processing");
            postProcess();

            syncPhase = SYNC_PHASE_SAVE_SYNC_STATE;
            App.log.info("Saving sync state");
            saveSyncState();
        } else
            App.log.info("Remote collection didn't change, skipping remote sync");

    } catch (IOException | ServiceUnavailableException e) {
        App.log.log(Level.WARNING, "I/O exception during sync, trying again later", e);
        syncResult.stats.numIoExceptions++;

        if (e instanceof ServiceUnavailableException) {
            Date retryAfter = ((ServiceUnavailableException) e).retryAfter;
            if (retryAfter != null) {
                // how many seconds to wait? getTime() returns ms, so divide by 1000
                syncResult.delayUntil = (retryAfter.getTime() - new Date().getTime()) / 1000;
            }
        }

    } catch (Exception | OutOfMemoryError e) {
        final int messageString;

        if (e instanceof UnauthorizedException) {
            App.log.log(Level.SEVERE, "Not authorized anymore", e);
            messageString = R.string.sync_error_unauthorized;
            syncResult.stats.numAuthExceptions++;
        } else if (e instanceof HttpException || e instanceof DavException) {
            App.log.log(Level.SEVERE, "HTTP/DAV Exception during sync", e);
            messageString = R.string.sync_error_http_dav;
            syncResult.stats.numParseExceptions++;
        } else if (e instanceof CalendarStorageException || e instanceof ContactsStorageException) {
            App.log.log(Level.SEVERE, "Couldn't access local storage", e);
            messageString = R.string.sync_error_local_storage;
            syncResult.databaseError = true;
        } else {
            App.log.log(Level.SEVERE, "Unknown sync error", e);
            messageString = R.string.sync_error;
            syncResult.stats.numParseExceptions++;
        }

        final Intent detailsIntent;
        if (e instanceof UnauthorizedException) {
            detailsIntent = new Intent(context, AccountSettingsActivity.class);
            detailsIntent.putExtra(AccountSettingsActivity.EXTRA_ACCOUNT, account);
        } else {
            detailsIntent = new Intent(context, DebugInfoActivity.class);
            detailsIntent.putExtra(DebugInfoActivity.KEY_THROWABLE, e);
            detailsIntent.putExtra(DebugInfoActivity.KEY_ACCOUNT, account);
            detailsIntent.putExtra(DebugInfoActivity.KEY_AUTHORITY, authority);
            detailsIntent.putExtra(DebugInfoActivity.KEY_PHASE, syncPhase);
        }

        // to make the PendingIntent unique
        detailsIntent.setData(Uri.parse("uri://" + getClass().getName() + "/" + uniqueCollectionId));

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(R.drawable.ic_error_light).setLargeIcon(App.getLauncherBitmap(context))
                .setContentTitle(getSyncErrorTitle())
                .setContentIntent(
                        PendingIntent.getActivity(context, 0, detailsIntent, PendingIntent.FLAG_CANCEL_CURRENT))
                .setCategory(NotificationCompat.CATEGORY_ERROR);

        try {
            String[] phases = context.getResources().getStringArray(R.array.sync_error_phases);
            String message = context.getString(messageString, phases[syncPhase]);
            builder.setContentText(message);
        } catch (IndexOutOfBoundsException ex) {
            // should never happen
        }

        notificationManager.notify(uniqueCollectionId, notificationId(), builder.build());
    }
}

From source file:com.mycelium.wallet.lt.notification.GcmIntentService.java

private void showAdNotification(String type) {
    Intent intent;// ww w.  j a  v  a  2 s .c o m
    if (LtApi.AD_TIME_OUT_NOTIFICATION_TYPE.equals(type)) {
        intent = PinProtectedActivity.createIntent(this,
                LtMainActivity.createIntent(this, LtMainActivity.TAB_TYPE.MY_ADS));
    } else {
        // We don't know this type, so we ignore it
        return;
    }
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    String title = getResources().getString(R.string.lt_mycelium_local_trader_title);
    String message = getResources().getString(R.string.lt_ad_deactivating_message);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentTitle(title)
            .setContentText(message).setSmallIcon(R.drawable.ic_launcher).setContentIntent(pIntent)
            .setAutoCancel(true);

    // Add ticker
    builder.setTicker(message);

    LocalTraderManager ltManager = MbwManager.getInstance(this).getLocalTraderManager();

    // Vibrate
    long[] pattern = { 500, 500 };
    builder.setVibrate(pattern);

    // Make a sound
    if (ltManager.getPlaySoundOnTradeNotification()) {
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (alarmSound != null) {
            builder.setSound(alarmSound);
        }
    }

    // Notify
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0, builder.build());
}

From source file:org.catrobat.catroid.utils.StatusBarNotificationManager.java

public void showUploadRejectedNotification(int id, int statusCode, String serverAnswer, Bundle bundle) {
    NotificationData notificationData = notificationDataMap.get(id);

    if (notificationData == null) {
        Log.d(TAG, "NotificationData is null.");
        return;//from w  w w.  ja va 2 s. c  o  m
    }
    NotificationCompat.Builder notificationBuilder = notificationData.getNotificationBuilder();
    notificationData.setNotificationTextDone(serverAnswer);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    notificationBuilder.setContentTitle(context.getResources().getText(R.string.notification_upload_rejected))
            .setContentText(serverAnswer)
            .setTicker(context.getResources().getText(R.string.notification_upload_rejected))
            .setSound(alarmSound).setStyle(new NotificationCompat.BigTextStyle().bigText(serverAnswer))
            .setProgress(0, 0, false).setAutoCancel(true).setPriority(Notification.PRIORITY_MAX)
            .setOngoing(false);

    switch (statusCode) {
    case Constants.STATUS_CODE_INTERNAL_SERVER_ERROR:
    case Constants.STATUS_CODE_UPLOAD_MISSING_DATA:
    case Constants.STATUS_CODE_UPLOAD_INVALID_CHECKSUM:
    case Constants.STATUS_CODE_UPLOAD_COPY_FAILED:
    case Constants.STATUS_CODE_UPLOAD_UNZIP_FAILED:
    case Constants.STATUS_CODE_UPLOAD_MISSING_XML:
    case Constants.STATUS_CODE_UPLOAD_RENAME_FAILED:
    case Constants.STATUS_CODE_UPLOAD_SAVE_THUMBNAIL_FAILED:
        Intent actionIntentRetryUpload = new Intent(context, NotificationActionService.class)
                .setAction(ACTION_RETRY_UPLOAD);
        actionIntentRetryUpload.putExtra("bundle", bundle);

        PendingIntent actionPendingIntentRetryUpload = PendingIntent.getService(context, id,
                actionIntentRetryUpload, PendingIntent.FLAG_CANCEL_CURRENT);
        notificationBuilder.addAction(android.R.drawable.ic_popup_sync,
                context.getResources().getString(R.string.notification_upload_retry),
                actionPendingIntentRetryUpload);

        Intent actionIntentCancelUpload = new Intent(context, NotificationActionService.class)
                .setAction(ACTION_CANCEL_UPLOAD);
        actionIntentCancelUpload.putExtra("bundle", bundle);
        PendingIntent actionPendingIntentCancelUpload = PendingIntent.getService(context, id,
                actionIntentCancelUpload, PendingIntent.FLAG_ONE_SHOT);
        notificationBuilder.addAction(android.R.drawable.ic_menu_close_clear_cancel,
                context.getResources().getString(R.string.cancel_button), actionPendingIntentCancelUpload);

        break;
    case Constants.STATUS_CODE_UPLOAD_MISSING_CHECKSUM:
    case Constants.STATUS_CODE_UPLOAD_OLD_CATROBAT_LANGUAGE:
    case Constants.STATUS_CODE_UPLOAD_OLD_CATROBAT_VERSION:
        Intent actionIntentUpdatePocketCodeVersion = new Intent(context, NotificationActionService.class)
                .setAction(ACTION_UPDATE_POCKET_CODE_VERSION).putExtra("notificationId", id);
        PendingIntent actionPendingIntentUpdatePocketCodeVersion = PendingIntent.getService(context, id,
                actionIntentUpdatePocketCodeVersion, PendingIntent.FLAG_ONE_SHOT);
        notificationBuilder.addAction(R.drawable.ic_launcher,
                context.getResources().getString(R.string.notification_open_play_store),
                actionPendingIntentUpdatePocketCodeVersion);
        break;

    default:
        notificationDataMap.put(id, notificationData);
        Intent openIntent = new Intent(context, MainMenuActivity.class);
        openIntent.setAction(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                .putExtra(EXTRA_PROJECT_NAME, bundle.getString("projectName"));

        PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, openIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        notificationData.setPendingIntent(pendingIntent);
        showOrUpdateNotification(id, MAXIMUM_PERCENT);
        return;
    }

    notificationBuilder.setContentIntent(notificationData.getPendingIntent());

    notificationDataMap.put(id, notificationData);
    notificationManager.notify(id, notificationBuilder.build());
}

From source file:com.kentli.cycletrack.RecordingService.java

private void setNotification() {
    CharSequence tickerText = "Recording...";
    long when = System.currentTimeMillis();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(RecordingService.this)
            .setContentTitle("CycleTracks - Recording").setContentText("Tap to finish your trip")
            .setSmallIcon(R.drawable.icon_notification).setTicker(tickerText).setWhen(when).setOngoing(true);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(RecordingService.this);
    stackBuilder.addNextIntent(new Intent(RecordingService.this, RecordingActivity.class));
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(resultPendingIntent);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(11, builder.build());

}

From source file:com.scooter1556.sms.android.manager.MediaNotificationManager.java

private PendingIntent createContentIntent(MediaDescriptionCompat description) {
    Intent intent = new Intent(mediaService, HomeActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra(HomeActivity.EXTRA_START_FULLSCREEN, true);

    if (description != null) {
        intent.putExtra(HomeActivity.EXTRA_CURRENT_MEDIA_DESCRIPTION, description);
    }/*from w  w w  . j a va  2s .c  o  m*/

    return PendingIntent.getActivity(mediaService, REQUEST_CODE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.saarang.samples.apps.iosched.gcm.command.NotificationCommand.java

private void processCommand(Context context, NotificationCommandModel command) {
    // Check format
    if (!"1.0.00".equals(command.format)) {
        LogUtils.LOGW(TAG, "GCM notification command has unrecognized format: " + command.format);
        return;/*from  ww  w . java  2s .c o m*/
    }

    // Check app version
    if (!TextUtils.isEmpty(command.minVersion) || !TextUtils.isEmpty(command.maxVersion)) {
        LogUtils.LOGD(TAG, "Command has version range.");
        int minVersion = 0;
        int maxVersion = Integer.MAX_VALUE;
        try {
            if (!TextUtils.isEmpty(command.minVersion)) {
                minVersion = Integer.parseInt(command.minVersion);
            }
            if (!TextUtils.isEmpty(command.maxVersion)) {
                maxVersion = Integer.parseInt(command.maxVersion);
            }
            LogUtils.LOGD(TAG, "Version range: " + minVersion + " - " + maxVersion);
            PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            LogUtils.LOGD(TAG, "My version code: " + pinfo.versionCode);
            if (pinfo.versionCode < minVersion) {
                LogUtils.LOGD(TAG, "Skipping command because our version is too old, " + pinfo.versionCode
                        + " < " + minVersion);
                return;
            }
            if (pinfo.versionCode > maxVersion) {
                LogUtils.LOGD(TAG, "Skipping command because our version is too new, " + pinfo.versionCode
                        + " > " + maxVersion);
                return;
            }
        } catch (NumberFormatException ex) {
            LogUtils.LOGE(TAG,
                    "Version spec badly formatted: min=" + command.minVersion + ", max=" + command.maxVersion);
            return;
        } catch (Exception ex) {
            LogUtils.LOGE(TAG, "Unexpected problem doing version check.", ex);
            return;
        }
    }

    // Check if we are the right audience
    LogUtils.LOGD(TAG, "Checking audience: " + command.audience);
    if ("remote".equals(command.audience)) {
        if (PrefUtils.isAttendeeAtVenue(context)) {
            LogUtils.LOGD(TAG, "Ignoring notification because audience is remote and attendee is on-site");
            return;
        } else {
            LogUtils.LOGD(TAG, "Relevant (attendee is remote).");
        }
    } else if ("local".equals(command.audience)) {
        if (!PrefUtils.isAttendeeAtVenue(context)) {
            LogUtils.LOGD(TAG, "Ignoring notification because audience is on-site and attendee is remote.");
            return;
        } else {
            LogUtils.LOGD(TAG, "Relevant (attendee is local).");
        }
    } else if ("all".equals(command.audience)) {
        LogUtils.LOGD(TAG, "Relevant (audience is 'all').");
    } else {
        LogUtils.LOGE(TAG, "Invalid audience on GCM notification command: " + command.audience);
        return;
    }

    // Check if it expired
    Date expiry = command.expiry == null ? null : TimeUtils.parseTimestamp(command.expiry);
    if (expiry == null) {
        LogUtils.LOGW(TAG, "Failed to parse expiry field of GCM notification command: " + command.expiry);
        return;
    } else if (expiry.getTime() < UIUtils.getCurrentTime(context)) {
        LogUtils.LOGW(TAG, "Got expired GCM notification command. Expiry: " + expiry.toString());
        return;
    } else {
        LogUtils.LOGD(TAG, "Message is still valid (expiry is in the future: " + expiry.toString() + ")");
    }

    // decide the intent that will be fired when the user clicks the notification
    Intent intent;
    if (TextUtils.isEmpty(command.dialogText)) {
        // notification leads directly to the URL, no dialog
        if (TextUtils.isEmpty(command.url)) {
            intent = new Intent(context, MyScheduleActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(command.url));
        }
    } else {
        // use a dialog
        intent = new Intent(context, MyScheduleActivity.class)
                .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_TITLE,
                command.dialogTitle == null ? "" : command.dialogTitle);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_MESSAGE,
                command.dialogText == null ? "" : command.dialogText);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_YES,
                command.dialogYes == null ? "OK" : command.dialogYes);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_NO, command.dialogNo == null ? "" : command.dialogNo);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_URL, command.url == null ? "" : command.url);
    }

    final String title = TextUtils.isEmpty(command.title)
            ? context.getString(com.saarang.samples.apps.iosched.R.string.app_name)
            : command.title;
    final String message = TextUtils.isEmpty(command.message) ? "" : command.message;

    // fire the notification
    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0,
            new NotificationCompat.Builder(context).setWhen(System.currentTimeMillis())
                    .setSmallIcon(com.saarang.samples.apps.iosched.R.drawable.ic_stat_notification)
                    .setTicker(command.message).setContentTitle(title).setContentText(message)
                    //.setColor(context.getResources().getColor(R.color.theme_primary))
                    // Note: setColor() is available in the support lib v21+.
                    // We commented it out because we want the source to compile 
                    // against support lib v20. If you are using support lib
                    // v21 or above on Android L, uncomment this line.
                    .setContentIntent(
                            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))
                    .setAutoCancel(true).build());
}

From source file:com.glanznig.beepme.BeeperApp.java

public void setTimer() {
    if (isBeeperActive()) {
        Calendar alarmTime = Calendar.getInstance();
        Calendar alarmTimeUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

        if (timerProfile == null) {
            setTimerProfile();/*from  w  w w . j a v a  2  s.  c o m*/
        }

        long timer = timerProfile.getTimer(this.getApplicationContext());
        alarmTime.add(Calendar.SECOND, (int) timer);
        //Log.i(TAG, "alarm in " + timer + " seconds.");
        alarmTimeUTC.add(Calendar.SECOND, (int) timer);
        getPreferences().setScheduledBeepId(new ScheduledBeepTable(this.getApplicationContext())
                .addScheduledBeep(alarmTime.getTimeInMillis(), getPreferences().getUptimeId()));

        Intent intent = new Intent(this, BeepActivity.class);
        PendingIntent alarmIntent = PendingIntent.getActivity(this, ALARM_INTENT_ID, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager manager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
        manager.set(AlarmManager.RTC_WAKEUP, alarmTimeUTC.getTimeInMillis(), alarmIntent);
    }
}

From source file:com.jereksel.rommanager.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.

    switch (item.getItemId()) {
    case R.id.delete_xml:

        new Thread() {
            public void run() {

                runOnUiThread(new Runnable() {
                    @Override/*from   ww w. j  a  va  2s. c o  m*/
                    public void run() {
                        Dialog = ProgressDialog.show(context, "Downloading/Preparing Data..", "Please wait",
                                true, false);
                    }
                });

                DownloadXML array;

                array = new DownloadXML(context, true);
                (array).start();

                try {
                    array.join();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Dialog.dismiss();
                        Intent mStartActivity = new Intent(context, MainActivity.class);
                        int mPendingIntentId = 123456;
                        PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,
                                mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
                        AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
                        System.exit(0);

                    }
                });

            }
        }.start();
        break;

    case R.id.about_screen:
        Intent in = new Intent(context, AboutScreen.class);
        startActivity(in);
        break;

    case R.id.changelog_dialog:
        Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.AppChangelog));
        builder.setCancelable(true);
        AlertDialog dialog = builder.create();
        dialog.show();
        break;
    }

    return mDrawerToggle.onOptionsItemSelected(item);

}

From source file:com.granita.tasks.notification.NotificationActionUtils.java

/**
 * Creates and displays an Undo notification for the specified {@link NotificationAction}.
 *///from w w w. j ava  2s . c o m
public static void createUndoNotification(final Context context, NotificationAction action) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContentTitle(context.getString(action.getActionTextResId()

    ));
    builder.setSmallIcon(R.drawable.ic_notification);
    builder.setWhen(action.getWhen());

    // disable sound & vibration
    builder.setDefaults(0);

    final RemoteViews undoView = new RemoteViews(context.getPackageName(), R.layout.undo_notification);
    undoView.setTextViewText(R.id.description_text, context.getString(action.mActionTextResId));

    final String packageName = context.getPackageName();

    final Intent clickIntent = new Intent(ACTION_UNDO);
    clickIntent.setPackage(packageName);
    putNotificationActionExtra(clickIntent, action);
    final PendingIntent clickPendingIntent = PendingIntent.getService(context, action.getNotificationId(),
            clickIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    undoView.setOnClickPendingIntent(R.id.status_bar_latest_event_content, clickPendingIntent);
    builder.setContent(undoView);

    // When the notification is cleared, we perform the destructive action
    final Intent deleteIntent = new Intent(ACTION_DESTRUCT);
    deleteIntent.setPackage(packageName);
    putNotificationActionExtra(deleteIntent, action);
    final PendingIntent deletePendingIntent = PendingIntent.getService(context, action.getNotificationId(),
            deleteIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setDeleteIntent(deletePendingIntent);

    final Notification notification = builder.build();

    final NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(action.getNotificationId(), notification);

    sUndoNotifications.put(action.getNotificationId(), action);
    sNotificationTimestamps.put(action.getNotificationId(), action.mWhen);
}