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:com.andrew.apollo.MusicPlaybackService.java

/**
 * Initializes the remote control client
 *///from  w ww.ja  v a  2  s. com
private void setUpRemoteControlClient() {
    final Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(mMediaButtonReceiverComponent);
    mRemoteControlClient = new RemoteControlClient(PendingIntent.getBroadcast(getApplicationContext(), 0,
            mediaButtonIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    try {
        if (mAudioManager != null) {
            mAudioManager.registerRemoteControlClient(mRemoteControlClient);
        }
    } catch (Throwable t) {
        // seems like this doesn't work on some devices where it requires MODIFY_PHONE_STATE
        // which is a permission only given to system apps, not third party apps.
    }

    // Flags for the media transport control that this client supports.
    int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP;

    flags |= RemoteControlClient.FLAG_KEY_MEDIA_POSITION_UPDATE;
    mRemoteControlClient.setOnGetPlaybackPositionListener(this::position);
    mRemoteControlClient.setPlaybackPositionUpdateListener(this::seek);

    mRemoteControlClient.setTransportControlFlags(flags);
}

From source file:com.aware.Aware.java

/**
 * Starts a plugin. Expects the package name of the plugin.<br/>
 * It checks if the plugin does exist on the phone. If it doesn't, it will request the user to install it automatically.
 * @param context// ww w.  j av a 2 s.c om
 * @param package_name
 */
public static void startPlugin(Context context, String package_name) {
    //Check if plugin is installed. If not, ask user to download it.
    Cursor is_installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null,
            Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null, null);
    if (is_installed != null && is_installed.moveToFirst()) {
        //We might just have it cached, but not installed
        if (isClassAvailable(context, package_name, "Plugin")) {
            //it's installed, start it!
            Intent plugin = new Intent();
            plugin.setClassName(package_name, package_name + ".Plugin");
            context.startService(plugin);
            if (Aware.DEBUG)
                Log.d(TAG, package_name + " started...");

            ContentValues rowData = new ContentValues();
            rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON);
            context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData,
                    Aware_Plugins.PLUGIN_PACKAGE_NAME + " LIKE '" + package_name + "'", null);
            is_installed.close();
            return;
        }
        is_installed.close();
    }

    HttpResponse response = new Https(awareContext)
            .dataGET("https://api.awareframework.com/index.php/plugins/get_plugin/" + package_name);
    if (response != null && response.getStatusLine().getStatusCode() == 200) {
        try {
            String data = EntityUtils.toString(response.getEntity());
            if (data.equals("[]"))
                return;

            JSONObject json_package = new JSONObject(data);

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
            mBuilder.setSmallIcon(R.drawable.ic_stat_aware_plugin_dependency);
            mBuilder.setContentTitle("AWARE");
            mBuilder.setContentText("Plugin missing: " + json_package.getString("title") + ". Tap to install.");
            mBuilder.setDefaults(Notification.DEFAULT_ALL);
            mBuilder.setAutoCancel(true);

            Intent pluginIntent = new Intent(context, DownloadPluginService.class);
            pluginIntent.putExtra("package_name", package_name);
            pluginIntent.putExtra("is_update", false);

            PendingIntent clickIntent = PendingIntent.getService(context, 0, pluginIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(clickIntent);
            NotificationManager notManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notManager.notify(json_package.getInt("id"), mBuilder.build());

        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.cmu.mpcs.dashboard.TagViewer.java

private String alarmSetting(String settingString) {
    if (settingString.contains("set alarm")) {
        /** Set Alarm **/

        String hour = settingString.substring(settingString.indexOf("#") + 1, settingString.indexOf("*"));
        String minute = settingString.substring(settingString.indexOf("*") + 1, settingString.indexOf("|"));

        Log.d("timePicker", hour + ":" + minute);

        int hr = Integer.parseInt(hour);
        int min = Integer.parseInt(minute);

        Log.d("Alarm", "hr:" + hr + "min:" + min);

        Calendar cal = Calendar.getInstance();
        // add minutes to the calendar object
        ///*from  w ww .  j a va2  s.c o m*/
        cal.set(Calendar.HOUR_OF_DAY, hr);
        cal.set(Calendar.MINUTE, min);
        cal.set(Calendar.SECOND, 0);
        // cal.add(Calendar.MINUTE, 1);
        Intent alarmintent = new Intent(getApplicationContext(), AlarmReceiver.class);
        alarmintent.putExtra("title", "Alarm for " + hour + ":" + minute);
        alarmintent.putExtra("note", "Touch to turn off Alarm");
        // HELLO_ID is a static variable that must be
        // initialised at the BEGINNING OF CLASS with 1;

        PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), HELLO_ID, alarmintent,
                PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
        // VERY IMPORTANT TO SET FLAG_UPDATE_CURRENT...
        // this will send correct extra's informations
        // to
        // AlarmReceiver Class
        // Get the AlarmManager service

        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
        Log.i("Alarm", "AlarmSet" + cal.toString());

        // /** Auto-sync **/
        //
        // if (!ContentResolver.getMasterSyncAutomatically())
        // ContentResolver.setMasterSyncAutomatically(true);
        // else {
        // ContentResolver.setMasterSyncAutomatically(false);
        // }

        return ("AlarmSet for : " + hour + ":" + min + "\n");

    }
    return ("");

}

From source file:com.ravi.apps.android.newsbytes.sync.NewsSyncAdapter.java

/**
 * Notifies the user that fresh news updates are now available.
 *//*from w  w  w  .j a va 2s  . co  m*/
private void sendNewsNotification(Context context) {
    // Create the intent to open the app when the user taps on the notification.
    Intent mainIntent = new Intent(context, MainActivity.class);

    // Create the stack builder object.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    // Add the intent to the top of the stack.
    stackBuilder.addNextIntent(mainIntent);

    // Get a pending intent containing the entire back stack.
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification builder object.
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Set the pending intent onto the notification.
    builder.setContentIntent(pendingIntent);

    // Set the notification to automatically dismiss after the user taps it.
    builder.setAutoCancel(true);

    // Set the notification title and text.
    builder.setContentTitle(context.getString(R.string.app_name))
            .setContentText(context.getString(R.string.msg_notification_text));

    // Set the notification ticker.
    builder.setTicker(context.getString(R.string.msg_notification_text));

    // Set the notification large and small icons.
    builder.setSmallIcon(R.drawable.ic_notify_small)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_notify_large));

    // Send the notification.
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(context.NOTIFICATION_SERVICE);
    notificationManager.notify(NEWS_NOTIFICATION_ID, builder.build());
}

From source file:com.androidinspain.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.
 *//*from w ww . j a  v  a  2 s.  com*/
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(mAlarmManager, nextExpiringTimer.getExpirationTime(), pi);
    }
}

From source file:androidVNC.VncCanvasActivity.java

@Override
public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    database = new VncDatabase(this);
    connection = new ConnectionBean();

    Intent i = getIntent();/*from  w  w  w .  java  2s  . c om*/
    Uri data = i.getData();
    if ((data != null) && (data.getScheme().equals("vnc"))) {
        String host = data.getHost();
        // This should not happen according to Uri contract, but bug introduced in Froyo (2.2)
        // has made this parsing of host necessary
        int index = host.indexOf(':');
        int port;
        if (index != -1) {
            try {
                port = Integer.parseInt(host.substring(index + 1));
            } catch (NumberFormatException nfe) {
                port = 0;
            }
            host = host.substring(0, index);
        } else {
            port = data.getPort();
        }
        if (host.equals(VncConstants.CONNECTION)) {
            if (connection.Gen_read(database.getReadableDatabase(), port)) {
                MostRecentBean bean = androidVNC.getMostRecent(database.getReadableDatabase());
                if (bean != null) {
                    bean.setConnectionId(connection.get_Id());
                    bean.Gen_update(database.getWritableDatabase());
                }
            }
        } else {
            connection.setAddress(host);
            connection.setNickname(connection.getAddress());
            connection.setPort(port);
            List<String> path = data.getPathSegments();
            if (path.size() >= 1) {
                connection.setColorModel(path.get(0));
            }
            if (path.size() >= 2) {
                connection.setPassword(path.get(1));
            }
            connection.save(database.getWritableDatabase());
        }
    } else {

        Bundle extras = i.getExtras();

        if (extras != null) {
            connection.Gen_populate((ContentValues) extras.getParcelable(VncConstants.CONNECTION));
        }
        if (connection.getPort() == 0)
            connection.setPort(5900);

        // Parse a HOST:PORT entry
        String host = connection.getAddress();
        if (host.indexOf(':') > -1) {
            String p = host.substring(host.indexOf(':') + 1);
            try {
                connection.setPort(Integer.parseInt(p));
            } catch (Exception e) {
            }
            connection.setAddress(host.substring(0, host.indexOf(':')));
        }
    }

    try {
        setContentView(fi.aalto.openoranges.project1.mcc.R.layout.canvas);
        vncCanvas = (VncCanvas) findViewById(fi.aalto.openoranges.project1.mcc.R.id.vnc_canvas);
        zoomer = (ZoomControls) findViewById(R.id.zoomer);
    } catch (Exception e) {
        e.printStackTrace();
    }

    vncCanvas.initializeVncCanvas(connection, new Runnable() {
        public void run() {
            setModes();
        }
    });
    vncCanvas.setOnGenericMotionListener(this);
    zoomer.hide();

    zoomer.setOnZoomInClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            showZoomer(true);
            vncCanvas.scaling.zoomIn(VncCanvasActivity.this);

        }

    });
    zoomer.setOnZoomOutClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            showZoomer(true);
            vncCanvas.scaling.zoomOut(VncCanvasActivity.this);

        }

    });
    zoomer.setOnZoomKeyboardClickListener(new View.OnClickListener() {

        /*
         * (non-Javadoc)
         *
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            InputMethodManager inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMgr.toggleSoftInput(0, 0);
        }

    });

    panner = new Panner(this, vncCanvas.handler);
    inputHandler = getInputHandlerById(fi.aalto.openoranges.project1.mcc.R.id.itemInputFitToScreen);

    mToken = getIntent().getStringExtra("token");
    mId = getIntent().getStringExtra("id");
    mName = getIntent().getStringExtra("name");

    //listener for the back-button
    registerClickCallback();

    //Notification in status bar
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(VncCanvasActivity.this)
            .setSmallIcon(R.drawable.icon_white).setContentTitle(mName + " running")
            .setContentText("Click to open the application screen");

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(VncCanvasActivity.this, VncCanvasActivity.class);
    resultIntent.setAction(Long.toString(System.currentTimeMillis()));
    mBuilder.setContentIntent(PendingIntent.getActivity(VncCanvasActivity.this, 0, resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mNotifyID allows you to update the notification later on.
    mNotificationManager.notify(mNotifyId, mBuilder.build());
    startService();
}

From source file:net.ben.subsonic.androidapp.util.Util.java

public static void showErrorNotification(final Context context, Handler handler, String title,
        Exception error) {//from w ww. ja va2 s  .com
    final NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    StringBuilder text = new StringBuilder();
    if (error.getMessage() != null) {
        text.append(error.getMessage()).append(" (");
    }
    text.append(error.getClass().getSimpleName());
    if (error.getMessage() != null) {
        text.append(")");
    }

    // Set the icon, scrolling text and timestamp
    final Notification notification = new Notification(android.R.drawable.stat_sys_warning, title,
            System.currentTimeMillis());
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // The PendingIntent to launch our activity if the user selects this notification
    Intent intent = new Intent(context, ErrorActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Constants.INTENT_EXTRA_NAME_ERROR, title + ".\n\n" + text);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, text, contentIntent);

    // Send the notification.
    handler.post(new Runnable() {
        @Override
        public void run() {
            notificationManager.cancel(Constants.NOTIFICATION_ID_ERROR);
            notificationManager.notify(Constants.NOTIFICATION_ID_ERROR, notification);
        }
    });
}

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

/**
 * Updates the notification controlling unexpired timers. This notification is only displayed
 * when the application is not open./*from   w ww. java2 s . co  m*/
 */
void updateNotification() {
    // Notifications should be hidden if the app is open.
    if (mNotificationModel.isApplicationInForeground()) {
        mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId());
        return;
    }

    // Filter the timers to just include unexpired ones.
    final List<Timer> unexpired = new ArrayList<>();
    for (Timer timer : getMutableTimers()) {
        if (timer.isRunning() || timer.isPaused()) {
            unexpired.add(timer);
        }
    }

    // If no unexpired timers exist, cancel the notification.
    if (unexpired.isEmpty()) {
        mNotificationManager.cancel(mNotificationModel.getUnexpiredTimerNotificationId());
        return;
    }

    // Sort the unexpired timers to locate the next one scheduled to expire.
    Collections.sort(unexpired, Timer.EXPIRY_COMPARATOR);
    final Timer timer = unexpired.get(0);
    final long remainingTime = timer.getRemainingTime();

    // Generate some descriptive text, a title, and some actions based on timer states.
    final String contentText;
    final String contentTitle;
    @DrawableRes
    int firstActionIconId, secondActionIconId = 0;
    @StringRes
    int firstActionTitleId, secondActionTitleId = 0;
    Intent firstActionIntent, secondActionIntent = null;

    if (unexpired.size() == 1) {
        contentText = formatElapsedTimeUntilExpiry(remainingTime);

        if (timer.isRunning()) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                contentTitle = mContext.getString(R.string.timer_notification_label);
            } else {
                contentTitle = timer.getLabel();
            }

            firstActionIconId = R.drawable.ic_pause_24dp;
            firstActionTitleId = R.string.timer_pause;
            firstActionIntent = new Intent(mContext, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            secondActionIconId = R.drawable.ic_add_24dp;
            secondActionTitleId = R.string.timer_plus_1_min;
            secondActionIntent = new Intent(mContext, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());
        } else {
            // Single timer is paused.
            contentTitle = mContext.getString(R.string.timer_paused);

            firstActionIconId = R.drawable.ic_start_24dp;
            firstActionTitleId = R.string.sw_resume_button;
            firstActionIntent = new Intent(mContext, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            secondActionIconId = R.drawable.ic_reset_24dp;
            secondActionTitleId = R.string.sw_reset_button;
            secondActionIntent = new Intent(mContext, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());
        }
    } else {
        if (timer.isRunning()) {
            // At least one timer is running.
            final String timeRemaining = formatElapsedTimeUntilExpiry(remainingTime);
            contentText = mContext.getString(R.string.next_timer_notif, timeRemaining);
            contentTitle = mContext.getString(R.string.timers_in_use, unexpired.size());
        } else {
            // All timers are paused.
            contentText = mContext.getString(R.string.all_timers_stopped_notif);
            contentTitle = mContext.getString(R.string.timers_stopped, unexpired.size());
        }

        firstActionIconId = R.drawable.ic_reset_24dp;
        firstActionTitleId = R.string.timer_reset_all;
        firstActionIntent = TimerService.createResetUnexpiredTimersIntent(mContext);
    }

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(mContext, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS)
            .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId())
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(mContext, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext).setOngoing(true)
            .setLocalOnly(true).setShowWhen(false).setAutoCancel(false).setContentText(contentText)
            .setContentTitle(contentTitle).setContentIntent(pendingShowApp)
            .setSmallIcon(R.drawable.stat_notify_timer).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

    final PendingIntent firstAction = PendingIntent.getService(mContext, 0, firstActionIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    final String firstActionTitle = mContext.getString(firstActionTitleId);
    builder.addAction(firstActionIconId, firstActionTitle, firstAction);

    if (secondActionIntent != null) {
        final PendingIntent secondAction = PendingIntent.getService(mContext, 0, secondActionIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        final String secondActionTitle = mContext.getString(secondActionTitleId);
        builder.addAction(secondActionIconId, secondActionTitle, secondAction);
    }

    // Update the notification.
    final Notification notification = builder.build();
    final int notificationId = mNotificationModel.getUnexpiredTimerNotificationId();
    mNotificationManager.notify(notificationId, notification);

    final Intent updateNotification = TimerService.createUpdateNotificationIntent(mContext);
    if (timer.isRunning() && remainingTime > MINUTE_IN_MILLIS) {
        // Schedule a callback to update the time-sensitive information of the running timer.
        final PendingIntent pi = PendingIntent.getService(mContext, 0, updateNotification,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

        final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS;
        final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange;

        schedulePendingIntent(triggerTime, pi);
    } else {
        // Cancel the update notification callback.
        final PendingIntent pi = PendingIntent.getService(mContext, 0, updateNotification,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE);
        if (pi != null) {
            mAlarmManager.cancel(pi);
            pi.cancel();
        }
    }
}

From source file:com.bonsai.wallet32.WalletService.java

private void showEventNotification(int noteId, int icon, String title, String msg) {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(icon)
            .setContentTitle(title).setContentText(msg).setAutoCancel(true).setDefaults(
                    Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);

    // Creates an explicit intent for an Activity in your app
    Intent intent = new Intent(this, ViewTransactionsActivity.class);

    // The stack builder object will contain an artificial back
    // stack for the started Activity.  This ensures that
    // navigating backward from the Activity leads out of your
    // application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ViewTransactionsActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(intent);/*ww w. ja  va2  s.  com*/
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    mNM.notify(noteId, mBuilder.build());
}