Example usage for android.app TaskStackBuilder getPendingIntent

List of usage examples for android.app TaskStackBuilder getPendingIntent

Introduction

In this page you can find the example usage for android.app TaskStackBuilder getPendingIntent.

Prototype

public PendingIntent getPendingIntent(int requestCode, @PendingIntent.Flags int flags) 

Source Link

Document

Obtain a PendingIntent for launching the task constructed by this builder so far.

Usage

From source file:org.secuso.privacyfriendlynetmonitor.ConnectionAnalysis.PassiveService.java

private void showWarningNotification() {
    //Set corresponding icon
    //if(Evidence.getMaxSeverity() > 2){
    //    mBuilder.setSmallIcon(R.mipmap.icon_warn_red);
    //    mBuilder.setLargeIcon(mWarnRed);
    //} else {/*w ww .  j  a v  a2  s . c  o  m*/
    //    mBuilder.setSmallIcon(R.mipmap.icon_warn_orange);
    //    mBuilder.setLargeIcon(mWarnOrange);
    //}
    //mBuilder.setContentText(mNotificationCount + " new warnings encountered.");

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

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(MainActivity.class);

    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // mId allows you to update the notification later on.
    mNotificationManager.notify(Const.LOG_TAG, 1, mBuilder.build());
}

From source file:com.android.madpausa.cardnotificationviewer.ConcreteNotificationListenerService.java

/**
 * sends the service notification//from   ww  w.java2 s  .  co  m
 */
private void handleServiceNotification() {

    NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    //filtering archived notification list
    List<StatusBarNotification> filteredArchivedNotificationList = baseNotificationFilter
            .applyFilter(archivedNotificationMap.values(), notificationGroups, true);
    int filteredArchiveddSize = filteredArchivedNotificationList.size();

    //should show notification only if there are notifications to be shown
    if (filteredArchiveddSize > 0) {
        NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);

        nBuilder.setContentTitle(
                String.format(getString(R.string.service_notification_text), filteredArchiveddSize));

        nBuilder.setSmallIcon(R.drawable.ic_notification);
        //gets the correct color resource, based on android version
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            nBuilder.setColor(getResources().getColor(R.color.app_background, null));
        else //noinspection deprecation
            nBuilder.setColor(getResources().getColor(R.color.app_background));

        //setting the intent
        Intent resultIntent = new Intent(this, MainActivity.class);

        //setting the extra containing the archived notifications
        resultIntent.putExtra(ARCHIVED_NOTIFICATIONS_EXTRA, new HashSet<>(archivedNotificationMap.keySet()));

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        nBuilder.setContentIntent(resultPendingIntent);

        //low priority, not min, as it has to show in the lockscreen
        nBuilder.setPriority(Notification.PRIORITY_LOW);

        Notification notification = nBuilder.build();

        //this notification should be sticky
        notification.flags |= Notification.FLAG_NO_CLEAR;
        nManager.notify(SERVICE_NOTIFICATION, 0, notification);
    }
    //else I should remove the notification
    else
        nManager.cancel(SERVICE_NOTIFICATION, 0);
}

From source file:com.jay.pea.mhealthapp2.utilityClasses.AlarmReceiver.java

/**
 * OnRecieve method that recieves calls form the AlertManager class and then applies some logic to fire notifications to the user.
 *
 * @param context//from   ww w . j  a v  a2s .  c  o m
 * @param intent
 */
@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "onRecieve");
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MedMinder");
    //Acquire the lock
    wl.acquire();

    dose = null;
    dose = (Dose) intent.getSerializableExtra(AlertManager.ALARMSTRING);
    Log.d(TAG,
            " This dose is " + dose.getMedication().getMedName() + "  " + dose.getDoseTime().toString(dtfTime));

    if (dose == null) {
        Log.d(TAG, "Alert object Extra is null");
    }

    //get the parent med
    Medication med = dose.getMedication();
    int alertCount = 0;
    for (DateTime doseDueDT : med.getDoseMap1().keySet()) {
        DateTime doseTakenDT = med.getDoseMap1().get(doseDueDT);
        if (doseDueDT.isBefore(new DateTime().now())
                && doseDueDT.isAfter(new DateTime().withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0))
                && doseTakenDT.equals(new DateTime(0))) {
            alertCount++;
        }
    }

    if (alertCount == 0) {
        return;
    }

    SharedPreferences sharedPref = context.getSharedPreferences("AlertCounter", 0);
    int alertCountPref = sharedPref.getInt(med.getMedName(), 0);
    SharedPreferences.Editor editor = sharedPref.edit();

    DateTime now = new DateTime().now();
    int notifID = dose.getMedication().getDbID();
    Random rand = new Random();
    //int notifID = rand.nextInt();
    Log.d(TAG, dose.getMedication().getDbID() + "   " + dose.getDoseTime().getMillisOfDay());

    if (dose.getTakenTime().toString(dtfDate).equals(new DateTime(0).toString(dtfDate))) {
        //            if ((dose.getDoseTime().getMillis() + alertMissedWindowArray[dose.getMedication().getFreq() - 1] * 2) > new DateTime().getMillis());
        String alertString = "You have " + alertCount + " missed doses for " + med.getMedName();
        if (alertCount == 1) {
            alertString = "You have a missed dose for " + med.getMedName();
        }

        //check if the dose is due +/- 15mins and advise that a dose is due.
        long diffMillis = dose.getDoseTime().getMillis() - new DateTime().now().getMillis();
        Log.d(TAG, diffMillis + "   dose time = " + dose.getDoseTime().getMillis() + " now= "
                + new DateTime().now().getMillis());
        boolean doseDue = Math.abs(diffMillis) < 1800000;
        if (doseDue) {
            alertString = dose.getMedication().getDose() + " of " + dose.getMedication().getMedName()
                    + " is due now.";
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.medminder_icon).setContentTitle("MedMinder").setContentText(alertString);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(context, MainActivity.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(context);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        // mId allows you to update the notification later on.
        mNotificationManager.notify(notifID, mBuilder.build());
        Log.d(TAG, " Notification sent " + notifID);
        //
        //
        //            editor.putInt(med.getMedName(), alertCount);
        //            editor.commit();

        //Release the lock
        wl.release();
    }
}

From source file:com.i2r.alan.rate_this_place.visitedplace.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *///from  w w w.j  a v  a 2 s  .  c om
private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), VisitedPlacesActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

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

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(com.i2r.alan.rate_this_place.R.mipmap.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                    com.i2r.alan.rate_this_place.R.mipmap.ic_launcher))
            .setColor(Color.RED).setContentTitle(notificationDetails)
            .setContentText(
                    getString(com.i2r.alan.rate_this_place.R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:ca.zadrox.dota2esportticker.service.ReminderAlarmService.java

private void notifyMatch(long matchId) {
    if (!PrefUtils.shouldShowMatchReminders(this)) {
        return;//  www . j av a  2  s . c om
    }

    final ContentResolver cr = getContentResolver();

    Cursor c = cr.query(MatchContract.SeriesEntry.CONTENT_URI, MatchDetailQuery.PROJECTION,
            SESSION_ID_WHERE_CLAUSE, new String[] { String.valueOf(matchId) }, null);

    if (!c.moveToNext()) {
        return;
    }

    Intent baseIntent = new Intent(this, MatchActivity.class);
    baseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

    Intent matchIntent = new Intent(this, MatchDetailActivity.class);
    matchIntent.putExtra(MatchDetailActivity.ARGS_GG_MATCH_ID, matchId);
    taskBuilder.addNextIntent(matchIntent);

    PendingIntent pi = taskBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

    final Resources res = getResources();
    String contentTitle = c.getString(MatchDetailQuery.TEAM_ONE_NAME) + " vs "
            + c.getString(MatchDetailQuery.TEAM_TWO_NAME);

    String contentText;

    long currentTime = TimeUtils.getUTCTime();
    long matchStart = c.getLong(MatchDetailQuery.DATE_TIME);

    int minutesLeft = (int) (matchStart - currentTime + 59000) / 60000;
    if (minutesLeft < 2 && minutesLeft >= 0) {
        minutesLeft = 1;
    }

    if (minutesLeft < 0) {
        contentText = "is scheduled to start now. (" + c.getString(MatchDetailQuery.TOURNAMENT_NAME) + ")";
    } else {
        contentText = "is scheduled to start in " + minutesLeft + " min. ("
                + c.getString(MatchDetailQuery.TOURNAMENT_NAME) + ")";
    }

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this).setContentTitle(contentTitle)
            .setContentText(contentText).setColor(res.getColor(R.color.theme_primary))
            .setTicker(contentTitle + " is about to start.")
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setLights(NOTIFICATION_ARGB_COLOR, NOTIFICATION_LED_ON_MS, NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(R.drawable.ic_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_DEFAULT).setAutoCancel(true);

    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    nm.notify(NOTIFICATION_ID, notifBuilder.build());
}

From source file:com.i2r.xue.rate_this_place.visitedplace.GeofenceTransitionsIntentService.java

/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 *//*  ww  w .  j a v a 2  s . c  om*/
private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), VisitedPlacesActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

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

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(com.i2r.xue.rate_this_place.R.mipmap.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                    com.i2r.xue.rate_this_place.R.mipmap.ic_launcher))
            .setColor(Color.RED).setContentTitle(notificationDetails)
            .setContentText(
                    getString(com.i2r.xue.rate_this_place.R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

From source file:org.protocoderrunner.apprunner.api.PApp.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@ProtocoderScript//from   ww w  . j  av a 2s. c  o  m
@APIMethod(description = "", example = "")
@APIParam(params = { "id", "title", "description" })
public void setNotification(int id, String title, String description) {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(a.get())
            .setSmallIcon(R.drawable.app_icon).setContentTitle(title).setContentText(description);
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(a.get(), AppRunnerActivity.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(a.get());
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(AppRunnerActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) a.get()
            .getSystemService(a.get().NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    mNotificationManager.notify(id, mBuilder.build());

}

From source file:org.fairphone.peaceofmind.PeaceOfMindBroadCastReceiver.java

/**
 * Sets the Peace of mind icon on the notification bar
 * @param putIcon if true the icon is put otherwise it is removed
 * @param wasInterrupted when true, an extra notification is sent to inform the user that Peace of mind was ended
 */// w  w w  .j a  va2s  .co  m
private void setPeaceOfMindIconInNotificationBar(boolean putIcon, boolean wasInterrupted) {

    NotificationManager manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (putIcon) {

        //just in case the user didn't clear it
        manager.cancel(PEACE_OF_MIND_INTERRUPTED_NOTIFICATION);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(R.drawable.peace_system_bar_icon)
                .setContentTitle(mContext.getResources().getString(R.string.app_name))
                .setContentText(mContext.getResources().getString(R.string.peace_on_notification));

        Intent resultIntent = new Intent(mContext, PeaceOfMindActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(PeaceOfMindActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(resultPendingIntent);

        Notification notificationWhileRunnig = builder.build();
        notificationWhileRunnig.flags |= Notification.FLAG_NO_CLEAR;
        // Add notification   
        manager.notify(PEACE_OF_MIND_ON_NOTIFICATION, notificationWhileRunnig);

    } else {
        manager.cancel(PEACE_OF_MIND_ON_NOTIFICATION);

        //send a notification saying that the peace was ended 
        if (wasInterrupted) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(R.drawable.peace_system_bar_icon).setAutoCancel(true)
                    .setContentTitle(mContext.getResources().getString(R.string.app_name))
                    .setContentText(mContext.getResources().getString(R.string.peace_off_notification))
                    .setTicker(mContext.getResources().getString(R.string.peace_off_notification));

            manager.notify(PEACE_OF_MIND_INTERRUPTED_NOTIFICATION, builder.build());
        }
    }
}

From source file:de.localtoast.launchit.BackgroundService.java

private void addNotificationIcon() {
    Context context = getBaseContext();
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.abc_ab_bottom_solid_dark_holo).setContentTitle("Launch it!")
            .setContentText("Touch for preferences").setOngoing(true);

    Intent resultIntent = new Intent(context, SettingsActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(SettingsActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1, mBuilder.build());
}

From source file:com.abhijitvalluri.android.fitnotifications.HomeFragment.java

private void initializeDemoButton() {
    mDemoTV.setOnClickListener(new View.OnClickListener() {
        @Override// w w  w .j  a  v a 2  s.com
        public void onClick(View v) {
            Bundle newExtra = new Bundle();

            NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
            String notificationText = "Sample notification subject";
            String notificationBigText = "Sample notification body. This is where the details of the notification will be shown.";

            StringBuilder sb = new StringBuilder();
            sb.append("[").append("example").append("] ");
            sb.append(notificationText);
            if (notificationBigText.length() > 0) {
                sb.append(" -- ").append(notificationBigText);
            }

            RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.custom_notification);
            contentView.setTextViewText(R.id.customNotificationText,
                    getString(R.string.placeholder_notification_text));
            builder.setSmallIcon(R.drawable.ic_sms_white_24dp).setContentText(sb.toString()).setExtras(newExtra)
                    .setContentTitle("Sample Notification Title").setContent(contentView);

            // Creates an explicit intent for the SettingsActivity in the app
            Intent settingsIntent = new Intent(mContext, SettingsActivity.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
            // the application to the Home screen.
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
            // Adds the back stack for the Intent (but not the Intent itself)
            stackBuilder.addParentStack(SettingsActivity.class);
            // Adds the Intent that starts the Activity to the top of the stack
            stackBuilder.addNextIntent(settingsIntent);
            PendingIntent settingsPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(settingsPendingIntent).setAutoCancel(true);

            ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
                    .notify(Constants.NOTIFICATION_ID, builder.build());

            Toast.makeText(mContext, getString(R.string.test_notification_sent), Toast.LENGTH_LONG).show();

            if (mDismissPlaceholderNotif) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ((NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE))
                                .cancel(Constants.NOTIFICATION_ID);
                    }
                }, mPlaceholderNotifDismissDelayMillis);
            }
        }
    });
}