Example usage for android.content Intent FLAG_ACTIVITY_CLEAR_TASK

List of usage examples for android.content Intent FLAG_ACTIVITY_CLEAR_TASK

Introduction

In this page you can find the example usage for android.content Intent FLAG_ACTIVITY_CLEAR_TASK.

Prototype

int FLAG_ACTIVITY_CLEAR_TASK

To view the source code for android.content Intent FLAG_ACTIVITY_CLEAR_TASK.

Click Source Link

Document

If set in an Intent passed to Context#startActivity Context.startActivity() , this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started.

Usage

From source file:com.gikoo5.hyphenate.ui.MainActivity.java

/**
 * ??dialog//from  w  ww .j  a v a2  s .c  o  m
 */
private void showConflictDialog() {
    isConflictDialogShow = true;
    EMHelper.getInstance().logout(false, null);
    String st = getResources().getString(R.string.Logoff_notification);
    if (!MainActivity.this.isFinishing()) {
        // clear up global variables
        try {
            if (conflictBuilder == null)
                conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
            conflictBuilder.setTitle(st);
            conflictBuilder.setMessage(R.string.connect_conflict);
            conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    conflictBuilder = null;
                    finish();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            conflictBuilder.setCancelable(false);
            conflictBuilder.create().show();
            isConflict = true;
        } catch (Exception e) {
            EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
        }

    }

}

From source file:cn.xcom.helper.chat.ui.MainActivity.java

/**
 * show the dialog when user logged into another device
 *//*w w  w  .j av a  2 s  .c  o  m*/
private void showConflictDialog() {
    isConflictDialogShow = true;
    DemoHelper.getInstance().logout(false, null);
    String st = getResources().getString(R.string.Logoff_notification);
    if (!MainActivity.this.isFinishing()) {
        // clear up global variables
        try {
            if (conflictBuilder == null)
                conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
            conflictBuilder.setTitle(st);
            conflictBuilder.setMessage(R.string.connect_conflict);
            conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    conflictBuilder = null;
                    finish();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            conflictBuilder.setCancelable(false);
            conflictBuilder.create().show();
            isConflict = true;
        } catch (Exception e) {
            EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
        }

    }

}

From source file:com.avcall.app.ui.MainActivity.java

/**
 * show the dialog when user logged into another device
 *///from   w w  w.j  a  va  2  s . co  m
private void showConflictDialog() {
    isConflictDialogShow = true;
    AvcallHelper.getInstance().logout(false, null);
    String st = getResources().getString(R.string.Logoff_notification);
    if (!MainActivity.this.isFinishing()) {
        // clear up global variables
        try {
            if (conflictBuilder == null)
                conflictBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
            conflictBuilder.setTitle(st);
            conflictBuilder.setMessage(R.string.connect_conflict);
            conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    conflictBuilder = null;
                    finish();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            conflictBuilder.setCancelable(false);
            conflictBuilder.create().show();
            isConflict = true;
        } catch (Exception e) {
            EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
        }

    }

}

From source file:com.android.messaging.ui.UIIntentsImpl.java

@Override
public PendingIntent getPendingIntentForSendingMessageToConversation(final Context context,
        final String conversationId, final String selfId, final boolean requiresMms, final int requestCode) {
    final Intent intent = new Intent(context, RemoteInputEntrypointActivity.class);
    intent.setAction(Intent.ACTION_SENDTO);
    // Ensure that the platform doesn't reuse PendingIntents across conversations
    intent.setData(MessagingContentProvider.buildConversationMetadataUri(conversationId));
    intent.putExtra(UIIntents.UI_INTENT_EXTRA_CONVERSATION_ID, conversationId);
    intent.putExtra(UIIntents.UI_INTENT_EXTRA_SELF_ID, selfId);
    intent.putExtra(UIIntents.UI_INTENT_EXTRA_REQUIRES_MMS, requiresMms);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    return getPendingIntentWithParentStack(context, intent, requestCode);
}

From source file:com.lannbox.rfduinotest.RFduinoService.java

private NotificationCompat.Builder buildServiceNotification() {
    Intent notificationIntent = new Intent(RFduinoService.this, MainActivity.class);
    notificationIntent.setAction("RFduinoTest_CallToMain");
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(RFduinoService.this, 0, notificationIntent, 0);

    Intent discoIntent = new Intent(RFduinoService.this, RFduinoService.class);
    discoIntent.setAction("ACTION_DISCONNECT");
    PendingIntent pDiscoIntent = PendingIntent.getService(RFduinoService.this, 0, discoIntent, 0);

    Intent connIntent = new Intent(RFduinoService.this, RFduinoService.class);
    connIntent.setAction("ACTION_CONNECT");
    PendingIntent pConnIntent = PendingIntent.getService(RFduinoService.this, 0, connIntent, 0);

    Intent stopIntent = new Intent(RFduinoService.this, RFduinoService.class);
    stopIntent.setAction("RFduinoService_Stop");
    PendingIntent pStopIntent = PendingIntent.getService(RFduinoService.this, 0, stopIntent, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(RFduinoService.this)
            .setContentTitle("Bluetooth Connection running").setTicker("BTLE Ticker")
            .setContentText("RFDuino connected").setSmallIcon(R.drawable.ic_launcher)
            //                    .setLargeIcon(
            //                          Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(pendingIntent).setOngoing(true) // maybe disable to allow closing with x-button?
            .addAction(android.R.drawable.ic_media_pause, "Disconnect", pDiscoIntent)
            .addAction(android.R.drawable.ic_media_play, "Connect", pConnIntent)
            .addAction(android.R.drawable.ic_delete, "Stop", pStopIntent);
    return mBuilder;
}

From source file:com.jordanfitzgibbon.rfduinohrm.RFduinoService.java

private NotificationCompat.Builder buildServiceNotification() {
    Intent notificationIntent = new Intent(RFduinoService.this,
            com.jordanfitzgibbon.rfduinohrm.MainActivity.class);
    notificationIntent.setAction("RFduinoTest_CallToMain");
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(RFduinoService.this, 0, notificationIntent, 0);

    Intent discoIntent = new Intent(RFduinoService.this, RFduinoService.class);
    discoIntent.setAction("ACTION_DISCONNECT");
    PendingIntent pDiscoIntent = PendingIntent.getService(RFduinoService.this, 0, discoIntent, 0);

    Intent connIntent = new Intent(RFduinoService.this, RFduinoService.class);
    connIntent.setAction("ACTION_CONNECT");
    PendingIntent pConnIntent = PendingIntent.getService(RFduinoService.this, 0, connIntent, 0);

    Intent stopIntent = new Intent(RFduinoService.this, RFduinoService.class);
    stopIntent.setAction("RFduinoService_Stop");
    PendingIntent pStopIntent = PendingIntent.getService(RFduinoService.this, 0, stopIntent, 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(RFduinoService.this)
            .setContentTitle("Bluetooth Connection running").setTicker("BTLE Ticker")
            .setContentText("RFDuino connected")
            //.setSmallIcon(R.drawable.ic_launcher)
            //                    .setLargeIcon(
            //                          Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(pendingIntent).setOngoing(true) // maybe disable to allow closing with x-button?
            .addAction(android.R.drawable.ic_media_pause, "Disconnect", pDiscoIntent)
            .addAction(android.R.drawable.ic_media_play, "Connect", pConnIntent)
            .addAction(android.R.drawable.ic_delete, "Stop", pStopIntent);
    return mBuilder;
}

From source file:com.farmerbb.taskbar.activity.ContextMenuActivity.java

@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.N_MR1)//from   w  w  w.j a  v  a 2s  .  c o  m
@Override
public boolean onPreferenceClick(Preference p) {
    UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
    LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
    boolean appIsValid = isStartButton || isOverflowMenu
            || !launcherApps.getActivityList(getIntent().getStringExtra("package_name"),
                    userManager.getUserForSerialNumber(userId)).isEmpty();

    if (appIsValid)
        switch (p.getKey()) {
        case "app_info":
            startFreeformActivity();
            launcherApps.startAppDetailsActivity(ComponentName.unflattenFromString(componentName),
                    userManager.getUserForSerialNumber(userId), null, null);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "uninstall":
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && isInMultiWindowMode()) {
                Intent intent2 = new Intent(ContextMenuActivity.this, DummyActivity.class);
                intent2.putExtra("uninstall", packageName);
                intent2.putExtra("user_id", userId);

                startFreeformActivity();
                startActivity(intent2);
            } else {
                startFreeformActivity();

                Intent intent2 = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName));
                intent2.putExtra(Intent.EXTRA_USER, userManager.getUserForSerialNumber(userId));

                try {
                    startActivity(intent2);
                } catch (ActivityNotFoundException e) {
                    /* Gracefully fail */ }
            }

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "open_taskbar_settings":
            startFreeformActivity();

            Intent intent2 = new Intent(this, MainActivity.class);
            intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent2);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "quit_taskbar":
            Intent quitIntent = new Intent("com.farmerbb.taskbar.QUIT");
            quitIntent.setPackage(BuildConfig.APPLICATION_ID);
            sendBroadcast(quitIntent);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "pin_app":
            PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
            if (pba.isPinned(componentName))
                pba.removePinnedApp(this, componentName);
            else {
                Intent intent = new Intent();
                intent.setComponent(ComponentName.unflattenFromString(componentName));

                LauncherActivityInfo appInfo = launcherApps.resolveActivity(intent,
                        userManager.getUserForSerialNumber(userId));
                if (appInfo != null) {
                    AppEntry newEntry = new AppEntry(packageName, componentName, appName,
                            IconCache.getInstance(this).getIcon(this, getPackageManager(), appInfo), true);

                    newEntry.setUserId(userId);
                    pba.addPinnedApp(this, newEntry);
                }
            }
            break;
        case "block_app":
            PinnedBlockedApps pba2 = PinnedBlockedApps.getInstance(this);
            if (pba2.isBlocked(componentName))
                pba2.removeBlockedApp(this, componentName);
            else {
                pba2.addBlockedApp(this, new AppEntry(packageName, componentName, appName, null, false));
            }
            break;
        case "show_window_sizes":
            getPreferenceScreen().removeAll();

            addPreferencesFromResource(R.xml.pref_context_menu_window_size_list);
            findPreference("window_size_standard").setOnPreferenceClickListener(this);
            findPreference("window_size_large").setOnPreferenceClickListener(this);
            findPreference("window_size_fullscreen").setOnPreferenceClickListener(this);
            findPreference("window_size_half_left").setOnPreferenceClickListener(this);
            findPreference("window_size_half_right").setOnPreferenceClickListener(this);
            findPreference("window_size_phone_size").setOnPreferenceClickListener(this);

            SharedPreferences pref = U.getSharedPreferences(this);
            if (pref.getBoolean("save_window_sizes", true)) {
                String windowSizePref = SavedWindowSizes.getInstance(this).getWindowSize(this, packageName);
                CharSequence title = findPreference("window_size_" + windowSizePref).getTitle();
                findPreference("window_size_" + windowSizePref).setTitle('\u2713' + " " + title);
            }

            if (U.isOPreview()) {
                U.showToast(this, R.string.window_sizes_not_available);
            }

            secondaryMenu = true;
            break;
        case "window_size_standard":
        case "window_size_large":
        case "window_size_fullscreen":
        case "window_size_half_left":
        case "window_size_half_right":
        case "window_size_phone_size":
            String windowSize = p.getKey().replace("window_size_", "");

            SharedPreferences pref2 = U.getSharedPreferences(this);
            if (pref2.getBoolean("save_window_sizes", true)) {
                SavedWindowSizes.getInstance(this).setWindowSize(this, packageName, windowSize);
            }

            startFreeformActivity();
            U.launchApp(getApplicationContext(), packageName, componentName, userId, windowSize, false, true);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "app_shortcuts":
            getPreferenceScreen().removeAll();
            generateShortcuts();

            secondaryMenu = true;
            break;
        case "shortcut_1":
        case "shortcut_2":
        case "shortcut_3":
        case "shortcut_4":
        case "shortcut_5":
            U.startShortcut(getApplicationContext(), packageName, componentName,
                    shortcuts.get(Integer.parseInt(p.getKey().replace("shortcut_", "")) - 1));

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "start_menu_apps":
            startFreeformActivity();

            Intent intent = null;

            SharedPreferences pref3 = U.getSharedPreferences(this);
            switch (pref3.getString("theme", "light")) {
            case "light":
                intent = new Intent(this, SelectAppActivity.class);
                break;
            case "dark":
                intent = new Intent(this, SelectAppActivityDark.class);
                break;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && pref3.getBoolean("freeform_hack", false)
                    && intent != null && isInMultiWindowMode()) {
                intent.putExtra("no_shadow", true);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);

                U.launchAppMaximized(getApplicationContext(), intent);
            } else
                startActivity(intent);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "volume":
            AudioManager audio = (AudioManager) getSystemService(AUDIO_SERVICE);
            audio.adjustSuggestedStreamVolume(AudioManager.ADJUST_SAME, AudioManager.USE_DEFAULT_STREAM_TYPE,
                    AudioManager.FLAG_SHOW_UI);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "file_manager":
            Intent fileManagerIntent;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                startFreeformActivity();
                fileManagerIntent = new Intent("android.provider.action.BROWSE");
            } else {
                fileManagerIntent = new Intent("android.provider.action.BROWSE_DOCUMENT_ROOT");
                fileManagerIntent.setComponent(
                        ComponentName.unflattenFromString("com.android.documentsui/.DocumentsActivity"));
            }

            fileManagerIntent.addCategory(Intent.CATEGORY_DEFAULT);
            fileManagerIntent
                    .setData(Uri.parse("content://com.android.externalstorage.documents/root/primary"));

            try {
                startActivity(fileManagerIntent);
            } catch (ActivityNotFoundException e) {
                U.showToast(this, R.string.lock_device_not_supported);
            }

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "system_settings":
            startFreeformActivity();

            Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);

            try {
                startActivity(settingsIntent);
            } catch (ActivityNotFoundException e) {
                U.showToast(this, R.string.lock_device_not_supported);
            }

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "lock_device":
            U.lockDevice(this);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "power_menu":
            U.sendAccessibilityAction(this, AccessibilityService.GLOBAL_ACTION_POWER_DIALOG);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        case "change_wallpaper":
            Intent intent3 = Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER),
                    getString(R.string.set_wallpaper));
            intent3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            U.launchAppMaximized(getApplicationContext(), intent3);

            showStartMenu = false;
            shouldHideTaskbar = true;
            contextMenuFix = false;
            break;
        }

    if (!secondaryMenu)
        finish();
    return true;
}

From source file:net.authorize.acceptsdk.sampleapp.androidpay.FullWalletConfirmationButtonFragment.java

private void moveToSuccessActivity(FullWallet fullWallet) {
    //FIXME: Need to check is it needed or not
    Wallet.Payments.notifyTransactionStatus(mGoogleApiClient, WalletUtil.createNotifyTransactionStatusRequest(
            fullWallet.getGoogleTransactionId(), NotifyTransactionStatusRequest.Status.SUCCESS));

    Intent intent = new Intent(getActivity(), OrderCompleteActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Constants.EXTRA_FULL_WALLET, fullWallet);
    startActivity(intent);//from   ww w .ja v a  2 s.  c  o  m
}

From source file:com.hyphenate.chatuidemo.ui.MainActivity.java

/**
 * show the dialog when user met some exception: such as login on another device, user removed or user forbidden
 *///from w  w w  . j ava  2s.  co m
private void showExceptionDialog(String exceptionType) {
    isExceptionDialogShow = true;
    DemoHelper.getInstance().logout(false, null);
    String st = getResources().getString(R.string.Logoff_notification);
    if (!MainActivity.this.isFinishing()) {
        // clear up global variables
        try {
            if (exceptionBuilder == null)
                exceptionBuilder = new android.app.AlertDialog.Builder(MainActivity.this);
            exceptionBuilder.setTitle(st);
            exceptionBuilder.setMessage(getExceptionMessageId(exceptionType));
            exceptionBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    exceptionBuilder = null;
                    isExceptionDialogShow = false;
                    finish();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            exceptionBuilder.setCancelable(false);
            exceptionBuilder.create().show();
            isConflict = true;
        } catch (Exception e) {
            EMLog.e(TAG, "---------color conflictBuilder error" + e.getMessage());
        }
    }
}

From source file:fr.paug.droidcon.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LOGD(TAG, "Considering notifying for time interval.");
    LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;//from   w w w.ja va 2  s  .  c  om
    }

    if (!PrefUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
            ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
            ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
    int starredCount = c.getCount();
    LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
    String singleSessionId = null;
    String singleSessionRoomId = null;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    while (c.moveToNext()) {
        singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
        singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
        starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
        LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
    }
    if (starredCount < 1) {
        return;
    }

    // Generates the pending intent which gets fired when the user taps on the notification.
    // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
    // related to navigation from notifications.
    Intent baseIntent = new Intent(this, MyScheduleActivity.class);
    baseIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

    // For a single session, tapping the notification should open the session details (b/15350787)
    if (starredCount == 1) {
        taskBuilder.addNextIntent(
                new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
    }

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

    final Resources res = getResources();
    String contentText;
    int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
    if (minutesLeft < 1) {
        minutesLeft = 1;
    }

    if (starredCount == 1) {
        contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
    } else {
        contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft,
                starredCount - 1);
    }

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
            //.setColor(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.
            .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS,
                    SessionAlarmService.NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
    if (minutesLeft > 5) {
        notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, intervalEnd, 5));
    }
    String bigContentTitle;
    if (starredCount == 1 && starredSessionTitles.size() > 0) {
        bigContentTitle = starredSessionTitles.get(0);
    } else {
        bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft,
                starredCount);
    }
    NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
            .setBigContentTitle(bigContentTitle);

    // Adds starred sessions starting at this time block to the notification.
    for (int i = 0; i < starredCount; i++) {
        richNotification.addLine(starredSessionTitles.get(i));
    }
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    LOGD(TAG, "Now showing notification.");
    nm.notify(NOTIFICATION_ID, richNotification.build());
}