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.xconns.peerdevicenet.core.CoreAPI.java

@TargetApi(5)
@Override//from   w  w  w. j a  va2s. co  m
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    Log.d(TAG, "RouterService onCreate()");

    timer = new ScheduledThreadPoolExecutor(1);

    linkMgr = new TransportManager(this, linkHandler);
    linkMgr.onResume();

    mMyDeviceInfo = new DeviceInfo();

    //loc wifi
    myWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mywifilock");
    myWifiLock.acquire();

    // init tcp connector
    mTCPConn = new TCPConnector(this);

    // notify others router is up by send ACTION_ROUTER_UP
    // eg. start remote intent service here
    Intent startupSignal = new Intent(Router.Intent.ACTION_ROUTER_UP);
    startService(startupSignal);

    // add notification and start service at foreground
    /*Notification notification = new Notification(R.drawable.router_icon,
    getText(R.string.router_notif_ticker),
    System.currentTimeMillis());*/
    // Instantiate a Builder object.
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle(getText(R.string.router_notif_title))
            .setTicker(getText(R.string.router_notif_ticker))
            .setContentText(getText(R.string.router_notif_message)).setSmallIcon(R.drawable.router_icon);
    //
    Intent notificationIntent = new Intent(Router.Intent.ACTION_CONNECTOR);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    builder.setContentIntent(pendingIntent);

    // using id of ticker text as notif id
    startForeground(R.string.router_notif_ticker, builder.build());

}

From source file:com.sdk.download.providers.downloads.DownloadNotification.java

private void updateActiveNotification(Collection<DownloadInfo> downloads) {
    // Collate the notifications
    mNotifications.clear();//  ww  w  .j  a  v  a2  s  . co m

    for (DownloadInfo download : downloads) {
        if (!isActiveAndVisible(download)) {
            continue;
        }

        String packageName = download.mPackage;
        long max = download.mTotalBytes;
        long progress = download.mCurrentBytes;
        long id = download.mId;
        String title = download.mTitle;
        if (title == null || title.length() == 0) {
            title = mContext.getResources().getString(R.string.zuimeia_sdk_download_download_unknown_title);
        }

        synchronized (mNotifications) {
            if (!mNotifications.containsKey(id)) {
                if (download.mStatus == Downloads.STATUS_RUNNING) {
                    NotificationItem item = new NotificationItem();
                    item.mId = id;
                    item.mPackageName = packageName;
                    item.mDescription = download.mDescription;
                    item.mStatus = download.mStatus;
                    item.addItem(title, progress, max);
                    mNotifications.put(download.mId, item);
                    if (download.mStatus == Downloads.STATUS_QUEUED_FOR_WIFI && item.mPausedText == null) {
                        item.mPausedText = mContext.getResources()
                                .getString(R.string.zuimeia_sdk_download_notification_need_wifi_for_size);
                    }
                } else {
                    mSystemFacade.cancelNotification(id);
                }
            }
        }
    }

    // Add the notifications
    for (NotificationItem item : mNotifications.values()) {
        // Build the notification object
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
        builder.setPriority(2);
        boolean hasPausedText = (item.mPausedText != null);
        int iconResource = android.R.drawable.stat_sys_download_done;
        if (hasPausedText) {
            iconResource = android.R.drawable.stat_sys_warning;
        }
        builder.setSmallIcon(iconResource);
        builder.setOngoing(true);

        boolean hasContentText = false;
        StringBuilder title = new StringBuilder(item.mTitles[0]);
        if (item.mTitleCount > 1) {
            title.append(mContext.getString(R.string.zuimeia_sdk_download_notification_filename_separator));
            title.append(item.mTitles[1]);
            if (item.mTitleCount > 2) {
                title.append(mContext.getString(R.string.zuimeia_sdk_download_notification_filename_extras,
                        new Object[] { Integer.valueOf(item.mTitleCount - 2) }));
            }
        } else if (!TextUtils.isEmpty(item.mDescription)) {
            builder.setContentText(item.mDescription);
            hasContentText = true;
        }
        builder.setContentTitle(title);// 

        if (hasPausedText) {// ??
            builder.setContentText(item.mPausedText);
        } else {
            builder.setProgress((int) item.mTotalTotal, (int) item.mTotalCurrent, item.mTotalTotal == -1);
            if (Build.VERSION.SDK_INT >= 11) {
                if (hasContentText) {
                    builder.setContentInfo(getDownloadingText(item.mTotalTotal, item.mTotalCurrent));
                }
            } else {// ?android 3.0
                builder.setContentText(String.format(mContext.getString(R.string.sdk_download_progress_percent),
                        getDownloadingText(item.mTotalTotal, item.mTotalCurrent)));
            }
        }
        // ?()
        // if (item.mStatus == Downloads.STATUS_PENDING || item.mStatus ==
        // Downloads.STATUS_RUNNING) {
        // Intent pauseIt = new
        // Intent(ZMDownloadReceiver.DOWNLOADRECEIVER_PAUSE);
        // pauseIt.setPackage(mContext.getPackageName());
        // Bundle bundle = new Bundle();
        // bundle.putLong(ZMDownloadReceiver.INTENT_DOWNLOAD_ID, item.mId);
        // bundle.putInt(ZMDownloadReceiver.INTENT_DOWNLOAD_STATUS,
        // item.mStatus);
        // pauseIt.putExtras(bundle);
        // builder.addAction(R.drawable.sdk_download_pause,
        // mContext.getString(R.string.zuimeia_sdk_download_notification_pause),
        // PendingIntent.getBroadcast(mContext, 0, pauseIt,
        // PendingIntent.FLAG_CANCEL_CURRENT));
        // }
        // ?
        if (item.mStatus != Downloads.STATUS_SUCCESS) {
            Intent cancelIt = new Intent(DownloadReceiver.DOWNLOAD_CANCEL);
            cancelIt.setPackage(mContext.getPackageName());
            Bundle bundle = new Bundle();
            bundle.putLong(DownloadReceiver.INTENT_DOWNLOAD_ID, item.mId);
            bundle.putInt(DownloadReceiver.INTENT_DOWNLOAD_STATUS, item.mStatus);
            cancelIt.putExtras(bundle);
            builder.addAction(R.drawable.sdk_download_download_cancel,
                    mContext.getString(R.string.sdk_download_notification_cancel),
                    PendingIntent.getBroadcast(mContext, 0, cancelIt, PendingIntent.FLAG_CANCEL_CURRENT));
        }

        Intent intent = new Intent(Constants.ACTION_LIST);
        intent.setClassName(mContext, DownloadReceiver.class.getName());
        intent.setData(ContentUris.withAppendedId(Downloads.getAllDownloadsContentURI(mContext), item.mId));
        intent.putExtra("multiple", item.mTitleCount > 1);

        builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0));

        mSystemFacade.postNotification(item.mId, builder.build());
    }
}

From source file:com.google.samples.apps.sergio.gcm.command.NotificationCommand.java

private void processCommand(Context context, NotificationCommandModel command) {
    // Check format
    if (!"1.0.00".equals(command.format)) {
        LOGW(TAG, "GCM notification command has unrecognized format: " + command.format);
        return;//from   w  ww  . ja  v  a2 s.  c  om
    }

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

    // Check if we are the right audience
    LOGD(TAG, "Checking audience: " + command.audience);
    if ("remote".equals(command.audience)) {
        if (PrefUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is remote and attendee is on-site");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is remote).");
        }
    } else if ("local".equals(command.audience)) {
        if (!PrefUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is on-site and attendee is remote.");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is local).");
        }
    } else if ("all".equals(command.audience)) {
        LOGD(TAG, "Relevant (audience is 'all').");
    } else {
        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) {
        LOGW(TAG, "Failed to parse expiry field of GCM notification command: " + command.expiry);
        return;
    } else if (expiry.getTime() < UIUtils.getCurrentTime(context)) {
        LOGW(TAG, "Got expired GCM notification command. Expiry: " + expiry.toString());
        return;
    } else {
        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(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(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.github.jvanhie.discogsscrobbler.util.NowPlayingService.java

private void play(final int trackNumber) {
    //do we even have something to play?
    if (trackList == null || trackList.size() == 0)
        return;/*from w w w.j a  va2 s. c  o m*/

    track = trackList.get(trackNumber);

    //don't play headings, on to the next! (if there is a next)
    if (track.type.equals("heading")) {
        if (trackNumber + 1 < trackList.size()) {
            play(trackNumber + 1);
        } else {
            stop();
        }
        return;
    }

    isPlaying = true;
    artist = track.artist;
    album = track.album;
    currentTrack = trackNumber;
    mNotificationBuilder.setContentTitle(track.title).setContentText(track.artist + " - " + track.album)
            .setWhen(System.currentTimeMillis()).setSmallIcon(android.R.drawable.ic_media_play);
    //fetch the duration (will return immediately when available) and start the alarm for when it's done
    mLastfm.getDuration(track, new Lastfm.LastfmWaiter() {
        @Override
        public void onResult(boolean success) {
            //set nowplaying, scrobbling happens on the alarm callback
            mLastfm.updateNowPlaying(track, new Lastfm.LastfmWaiter() {
                @Override
                public void onResult(boolean success) {
                    //the user already sees the notification, no need for extras notifications atm.
                }
            });

            //notify user
            startForeground(NOTIFICATION_ID, mNotificationBuilder.build());
            //update listeners to track change
            sendBroadcast(new Intent(TRACK_CHANGE));

            Intent intent = new Intent(NowPlayingService.this, NowPlayingAlarm.class);
            if (trackNumber < trackList.size() - 1) {
                intent.putExtra(NEXT_TRACK_ID, (trackNumber + 1));
                intent.putExtra(NEXT_TRACK_TITLE, trackList.get(trackNumber + 1).title);
            } else {
                //this is the last track, alarm will be used to stop the service (by issuing pos = -1 and title = first song title)
                intent.putExtra(NEXT_TRACK_ID, -1);
                intent.putExtra(NEXT_TRACK_TITLE, trackList.get(0).title);
            }
            mTrackStart = SystemClock.elapsedRealtime();
            int duration = Track.formatDurationToSeconds(track.duration);
            if (duration == 0)
                duration = Lastfm.DEFAULT_TRACK_DURATION;
            if (mTrackDone != 0)
                duration -= mTrackDone;
            mAlarmIntent = PendingIntent.getBroadcast(NowPlayingService.this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mTrackStart + duration * 1000,
                    mAlarmIntent);

        }
    });

}

From source file:de.quist.app.errorreporter.ExceptionReportService.java

private void sendReport(Intent intent) throws UnsupportedEncodingException, NameNotFoundException {
    Log.v(TAG, "Got request to report error: " + intent.toString());
    Uri server = getTargetUrl();/*from w  w  w.ja  v a 2  s  . c  o  m*/

    boolean isManualReport = intent.getBooleanExtra(EXTRA_MANUAL_REPORT, false);
    boolean isReportOnFroyo = isReportOnFroyo();
    boolean isFroyoOrAbove = isFroyoOrAbove();
    if (isFroyoOrAbove && !isManualReport && !isReportOnFroyo) {
        // We don't send automatic reports on froyo or above
        Log.d(TAG, "Don't send automatic report on froyo");
        return;
    }

    Set<String> fieldsToSend = getFieldsToSend();

    String stacktrace = intent.getStringExtra(EXTRA_STACK_TRACE);
    String exception = intent.getStringExtra(EXTRA_EXCEPTION_CLASS);
    String message = intent.getStringExtra(EXTRA_MESSAGE);
    long availableMemory = intent.getLongExtra(EXTRA_AVAILABLE_MEMORY, -1l);
    long totalMemory = intent.getLongExtra(EXTRA_TOTAL_MEMORY, -1l);
    String dateTime = intent.getStringExtra(EXTRA_EXCEPTION_TIME);
    String threadName = intent.getStringExtra(EXTRA_THREAD_NAME);
    String extraMessage = intent.getStringExtra(EXTRA_EXTRA_MESSAGE);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    addNameValuePair(params, fieldsToSend, "exStackTrace", stacktrace);
    addNameValuePair(params, fieldsToSend, "exClass", exception);
    addNameValuePair(params, fieldsToSend, "exDateTime", dateTime);
    addNameValuePair(params, fieldsToSend, "exMessage", message);
    addNameValuePair(params, fieldsToSend, "exThreadName", threadName);
    if (extraMessage != null)
        addNameValuePair(params, fieldsToSend, "extraMessage", extraMessage);
    if (availableMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devAvailableMemory", availableMemory + "");
    if (totalMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devTotalMemory", totalMemory + "");

    PackageManager pm = getPackageManager();
    try {
        PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
        addNameValuePair(params, fieldsToSend, "appVersionCode", packageInfo.versionCode + "");
        addNameValuePair(params, fieldsToSend, "appVersionName", packageInfo.versionName);
        addNameValuePair(params, fieldsToSend, "appPackageName", packageInfo.packageName);
    } catch (NameNotFoundException e) {
    }
    addNameValuePair(params, fieldsToSend, "devModel", android.os.Build.MODEL);
    addNameValuePair(params, fieldsToSend, "devSdk", android.os.Build.VERSION.SDK);
    addNameValuePair(params, fieldsToSend, "devReleaseVersion", android.os.Build.VERSION.RELEASE);

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(server.toString());
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    Log.d(TAG, "Created post request");

    try {
        httpClient.execute(post);
        Log.v(TAG, "Reported error: " + intent.toString());
    } catch (ClientProtocolException e) {
        // Ignore this kind of error
        Log.e(TAG, "Error while sending an error report", e);
    } catch (SSLException e) {
        Log.e(TAG, "Error while sending an error report", e);
    } catch (IOException e) {
        if (e instanceof SocketException && e.getMessage().contains("Permission denied")) {
            Log.e(TAG, "You don't have internet permission", e);
        } else {
            int maximumRetryCount = getMaximumRetryCount();
            int maximumExponent = getMaximumBackoffExponent();
            // Retry at a later point in time
            AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
            int exponent = intent.getIntExtra(EXTRA_CURRENT_RETRY_COUNT, 0);
            intent.putExtra(EXTRA_CURRENT_RETRY_COUNT, exponent + 1);
            PendingIntent operation = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (exponent >= maximumRetryCount) {
                // Discard error
                Log.w(TAG, "Error report reached the maximum retry count and will be discarded.\nStacktrace:\n"
                        + stacktrace);
                return;
            }
            if (exponent > maximumExponent) {
                exponent = maximumExponent;
            }
            long backoff = (1 << exponent) * 1000; // backoff in ms
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + backoff, operation);
        }
    }
}

From source file:com.meiste.greg.ptw.gcm.GcmIntentService.java

private void showResultsNotification(final Context context, final String race) {
    // Only show notification if user wants results notifications
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (prefs.getBoolean(EditPreferences.KEY_NOTIFY_RESULTS, true)
            && mContainer.getBoolean(GtmHelper.KEY_GAME_ENABLED)) {
        final Intent notificationIntent = new Intent(context, MainActivity.class);
        notificationIntent.putExtra(PTW.INTENT_EXTRA_TAB, 2);
        final PendingIntent pi = PendingIntent.getActivity(context, PI_REQ_CODE, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        int defaults = 0;
        if (prefs.getBoolean(EditPreferences.KEY_NOTIFY_VIBRATE, true))
            defaults |= Notification.DEFAULT_VIBRATE;
        if (prefs.getBoolean(EditPreferences.KEY_NOTIFY_LED, true))
            defaults |= Notification.DEFAULT_LIGHTS;

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.drawable.ic_stat_steering_wheel)
                .setTicker(context.getString(R.string.remind_results_notify, race))
                .setContentTitle(context.getString(R.string.app_name))
                .setContentText(context.getString(R.string.remind_results_notify, race)).setContentIntent(pi)
                .setAutoCancel(true).setDefaults(defaults).setSound(Uri
                        .parse(prefs.getString(EditPreferences.KEY_NOTIFY_RINGTONE, PTW.DEFAULT_NOTIFY_SND)));

        getNM(context).notify(R.string.remind_results_notify, builder.build());
    }/*  w  ww  . j a  v  a  2 s. c  o  m*/
}

From source file:com.pinplanet.pintact.GcmIntentService.java

private void sendDefaultNotification() {
    Intent it = new Intent(this, LeftDeckActivity.class);
    it.putExtra(LeftDeckActivity.SELECTED_OPTIONS, LeftDeckActivity.OPTION_NOTIFY);
    // add the following line would show Pintact to the preview page.
    // it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("Pintact Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText("New notification from Pintact"))
            .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
            .setContentText("New notification from Pintact");

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    SingletonLoginData.getInstance().mNotificationManager = mNotificationManager;
}

From source file:at.jclehner.rxdroid.NotificationReceiver.java

private PendingIntent createOperation(Bundle extras) {
    Intent intent = new Intent(mContext, NotificationReceiver.class);
    intent.setAction(Intent.ACTION_MAIN);

    if (extras != null)
        intent.putExtras(extras);/*  w w  w  .  ja v a  2 s .c om*/

    return PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:net.geniecode.ttr.ScheduleReceiver.java

@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void setNotification(Context context) {
    ScrollingText = context.getString(R.string.schedule_postponed_scroll);
    NotificationText = context.getString(R.string.schedule_postponed_notify);

    // Trigger a notification that, when clicked, will activate airplane mode
    mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, ActivateFlightMode.class), PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification;/*w  w w.  java2 s  . c  o  m*/

    if (android.os.Build.VERSION.SDK_INT >= 11) {
        Notification.Builder builder = new Notification.Builder(context);
        builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.ic_launcher).setTicker(ScrollingText)
                .setWhen(System.currentTimeMillis()).setAutoCancel(true).setOnlyAlertOnce(true)
                .setDefaults(Notification.DEFAULT_LIGHTS).setContentTitle(context.getText(R.string.app_name))
                .setContentText(NotificationText);
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = builder.build();
        } else {
            notification = builder.getNotification();
        }
    } else {
        notification = new Notification(R.drawable.ic_launcher, ScrollingText, System.currentTimeMillis());
        notification.setLatestEventInfo(context, context.getText(R.string.app_name), NotificationText,
                contentIntent);
        notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_LIGHTS;
    }
    mNotificationManager.notify(NOTIFICATION_ID, notification);
}

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

private static PendingIntent getCompleteActionIntent(Context context, int notificationId, Uri taskUri) {
    final Intent intent = new Intent(NotificationActionIntentService.ACTION_COMPLETE);

    intent.setPackage(context.getPackageName());
    intent.setData(taskUri);/*from   w  ww  .j a  va  2  s  .  c o  m*/
    intent.putExtra(EXTRA_NOTIFICATION_ID, notificationId);
    final PendingIntent pendingIntent = PendingIntent.getService(context, REQUEST_CODE_COMPLETE, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    return pendingIntent;
}