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.keylesspalace.tusky.MainActivity.java

private void changeAccount(long newSelectedId) {
    accountManager.setActiveAccount(newSelectedId);

    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivityWithSlideInAnimation(intent);
    finishWithoutSlideOutAnimation();//from  w w w . j  a  v  a  2  s .  co  m

    overridePendingTransition(R.anim.explode, R.anim.explode);
}

From source file:com.android.nfc.beam.BeamTransferManager.java

Intent buildViewIntent() {
    if (mPaths.size() == 0)
        return null;

    Intent viewIntent = new Intent(Intent.ACTION_VIEW);

    String filePath = mPaths.get(0);
    Uri mediaUri = mMediaUris.get(filePath);
    Uri uri = mediaUri != null ? mediaUri
            : FileProvider.getUriForFile(mContext, "com.google.android.nfc.fileprovider", new File(filePath));
    viewIntent.setDataAndTypeAndNormalize(uri, mMimeTypes.get(filePath));
    viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    return viewIntent;
}

From source file:com.example.bluetooth.RFduinoService.java

private NotificationCompat.Builder buildServiceNotification() {
    Intent notificationIntent = new Intent(RFduinoService.this, BluetoothActivity.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.example.android.bluetoothchat.BluetoothChatFragment2.java

public static void startVrGallery2(Context context, int type, String path, int currentSeek) {
    PackageInfo svrInstalled;//from   ww w  . ja v a  2s.  c om
    String SVR_PACKAGE_NAME_LOCAL = VR_GALLERY2_PKG_NAME;
    String SVR_ACTIVITY_NAME = VR_GALLERY2_ACTIVITY_NAME;
    try {
        svrInstalled = context.getPackageManager().getPackageInfo(SVR_PACKAGE_NAME_LOCAL, VR_VIEWTYPE_ALBUM);
    } catch (PackageManager.NameNotFoundException e) {
        svrInstalled = null;
    }
    if (svrInstalled != null) {
        Uri uri = Uri.parse("file://" + path);
        Intent intent = new Intent();
        intent.setClassName(SVR_PACKAGE_NAME_LOCAL, SVR_ACTIVITY_NAME);
        intent.setData(uri);
        intent.putExtra("viewmode", type);
        //            intent.putExtra("wait_title", "Wait Title");
        //            intent.putExtra("wait_message", "Wait Message");
        if (currentSeek > 0) {
            intent.putExtra("seek", currentSeek);
        }
        //            intent.setFlags(268500992);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(VR_VIEWTYPE_ALBUM, VR_VIEWTYPE_ALBUM);
        return;
    }
}

From source file:com.nxt.yn.app.ui.MainActivity.java

/**
 * ??dialog//from ww w .ja v a2s  .  co 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();
                    MyApplication.getInstance().cleanspf();
                    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.artemchep.horario.ui.activities.MainActivity.java

/**
 * Launches auth activity and finishes/*from  ww w  .  j  a  v a2s . c  o m*/
 * this one.
 */
private void switchToAuthActivity() {
    Intent intent = new Intent(this, AuthActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

    // Do not animate
    overridePendingTransition(0, 0);
}

From source file:androidx.navigation.NavController.java

/**
 * Checks the given Intent for a Navigation deep link and navigates to the deep link if present.
 * This is called automatically for you the first time you set the graph if you've passed in an
 * {@link Activity} as the context when constructing this NavController, but should be manually
 * called if your Activity receives new Intents in {@link Activity#onNewIntent(Intent)}.
 * <p>/*from   www .ja  v a  2s  .co  m*/
 * The types of Intents that are supported include:
 * <ul>
 *     <ol>Intents created by {@link NavDeepLinkBuilder} or
 *     {@link #createDeepLink()}. This assumes that the current graph shares
 *     the same hierarchy to get to the deep linked destination as when the deep link was
 *     constructed.</ol>
 *     <ol>Intents that include a {@link Intent#getData() data Uri}. This Uri will be checked
 *     against the Uri patterns added via {@link NavDestination#addDeepLink(String)}.</ol>
 * </ul>
 * <p>The {@link #getGraph() navigation graph} should be set before calling this method.</p>
 * @param intent The Intent that may contain a valid deep link
 * @return True if the navigation controller found a valid deep link and navigated to it.
 * @see NavDestination#addDeepLink(String)
 */
public boolean onHandleDeepLink(@Nullable Intent intent) {
    if (intent == null) {
        return false;
    }
    Bundle extras = intent.getExtras();
    int[] deepLink = extras != null ? extras.getIntArray(KEY_DEEP_LINK_IDS) : null;
    Bundle bundle = new Bundle();
    Bundle deepLinkExtras = extras != null ? extras.getBundle(KEY_DEEP_LINK_EXTRAS) : null;
    if (deepLinkExtras != null) {
        bundle.putAll(deepLinkExtras);
    }
    if ((deepLink == null || deepLink.length == 0) && intent.getData() != null) {
        Pair<NavDestination, Bundle> matchingDeepLink = mGraph.matchDeepLink(intent.getData());
        if (matchingDeepLink != null) {
            deepLink = matchingDeepLink.first.buildDeepLinkIds();
            bundle.putAll(matchingDeepLink.second);
        }
    }
    if (deepLink == null || deepLink.length == 0) {
        return false;
    }
    bundle.putParcelable(KEY_DEEP_LINK_INTENT, intent);
    int flags = intent.getFlags();
    if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 && (flags & Intent.FLAG_ACTIVITY_CLEAR_TASK) == 0) {
        // Someone called us with NEW_TASK, but we don't know what state our whole
        // task stack is in, so we need to manually restart the whole stack to
        // ensure we're in a predictably good state.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(mContext)
                .addNextIntentWithParentStack(intent);
        taskStackBuilder.startActivities();
        if (mActivity != null) {
            mActivity.finish();
        }
        return true;
    }
    if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        // Start with a cleared task starting at our root when we're on our own task
        if (!mBackStack.isEmpty()) {
            navigate(mGraph.getStartDestination(), bundle, new NavOptions.Builder()
                    .setPopUpTo(mGraph.getId(), true).setEnterAnim(0).setExitAnim(0).build());
        }
        int index = 0;
        while (index < deepLink.length) {
            int destinationId = deepLink[index++];
            NavDestination node = findDestination(destinationId);
            if (node == null) {
                throw new IllegalStateException("unknown destination during deep link: "
                        + NavDestination.getDisplayName(mContext, destinationId));
            }
            node.navigate(bundle, new NavOptions.Builder().setEnterAnim(0).setExitAnim(0).build());
        }
        return true;
    }
    // Assume we're on another apps' task and only start the final destination
    NavGraph graph = mGraph;
    for (int i = 0; i < deepLink.length; i++) {
        int destinationId = deepLink[i];
        NavDestination node = i == 0 ? mGraph : graph.findNode(destinationId);
        if (node == null) {
            throw new IllegalStateException("unknown destination during deep link: "
                    + NavDestination.getDisplayName(mContext, destinationId));
        }
        if (i != deepLink.length - 1) {
            // We're not at the final NavDestination yet, so keep going through the chain
            graph = (NavGraph) node;
        } else {
            // Navigate to the last NavDestination, clearing any existing destinations
            node.navigate(bundle, new NavOptions.Builder().setPopUpTo(mGraph.getId(), true).setEnterAnim(0)
                    .setExitAnim(0).build());
        }
    }
    return true;
}

From source file:cat.ereza.customactivityoncrash.CustomActivityOnCrash.java

/**
 * Given an Intent, restarts the app and launches a startActivity to that intent.
 * The flags NEW_TASK and CLEAR_TASK are set if the Intent does not have them, to ensure
 * the app stack is fully cleared.//  w w  w  .j  ava 2  s.c  o  m
 * If an event listener is provided, the restart app event is invoked.
 * Must only be used from your error activity.
 *
 * @param activity      The current error activity. Must not be null.
 * @param intent        The Intent. Must not be null.
 * @param eventListener The event listener as obtained by calling getEventListenerFromIntent.
 */
public static void restartApplicationWithIntent(Activity activity, Intent intent, EventListener eventListener) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    if (eventListener != null) {
        eventListener.onRestartAppFromErrorActivity();
    }
    activity.finish();
    activity.startActivity(intent);
    killCurrentProcess();
}

From source file:com.jjcamera.apps.iosched.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  .j a v a  2  s  . co m*/
    }

    if (!SettingsUtils.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 = null;
    try {
        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_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))
                .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));
        }
        /*if (starredCount == 1 && SettingsUtils.isAttendeeAtVenue(this)) {
        notifBuilder.addAction(R.drawable.ic_map_holo_dark,
                res.getString(R.string.title_map),
                createRoomMapIntent(singleSessionRoomId));
        }*/
        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());
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:com.example.android.bluetoothchat.BluetoothChatFragment2.java

private static void gearVRforVideofunctionality(Context context, String mVRfilePath) {
    PackageInfo svrInstalled;/*w w  w  .j  ava  2s. c o m*/
    String SVR_PACKAGE_NAME_LOCAL = VR_VIDEO_PKG_NAME;
    String SVR_ACTIVITY_NAME = VR_VIDEO_ACTIVITY_NAME;
    try {
        svrInstalled = context.getPackageManager().getPackageInfo(SVR_PACKAGE_NAME_LOCAL, VR_VIEWTYPE_ALBUM);
    } catch (PackageManager.NameNotFoundException e) {
        svrInstalled = null;
    }
    if (svrInstalled != null) {
        Uri uri = Uri.parse("file://" + mVRfilePath);
        Intent intent = new Intent();
        intent.setClassName(SVR_PACKAGE_NAME_LOCAL, SVR_ACTIVITY_NAME);
        intent.setData(uri);
        //            intent.putExtra("wait_title", context.getString(C0804R.string.SS_INSERT_DEVICE_INTO_GEAR_VR_HEADER_ABB));
        //            intent.putExtra("wait_message", context.getString(C0804R.string.f148xfc67daff));
        //            intent.setFlags(268500992);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(VR_VIEWTYPE_ALBUM, VR_VIEWTYPE_ALBUM);
        return;
    }
}