Removing an activity from the history stack
Asked Answered
D

16

402

My app shows a signup activity the first time the user runs the app, looks like:

  1. ActivitySplashScreen (welcome to game, sign up for an account?)
  2. ActivitySplashScreenSignUp (great, fill in this info)
  3. ActivityGameMain (main game screen)

so the activities launch each other in exactly that order, when the user clicks through a button on each screen.

When the user goes from activity #2 to #3, is it possible to wipe #1 and #2 off the history stack completely? I'd like it so that if the user is at #3, and hits the back button, they just go to the homescreen, instead of back to the splash screen.

I think I can accomplish this with tasks (ie. start a new task on #3) but wanted to see if there was simpler method,

Thanks

Disfigure answered 14/12, 2009 at 4:15 Comment(1)
After being in home screen, when user resumes your app does it take him to ActivitySplashScreen or ActivityGameMain?Promulgate
P
668

You can achieve this by setting the android:noHistory attribute to "true" in the relevant <activity> entries in your AndroidManifest.xml file. For example:

<activity
    android:name=".AnyActivity"
    android:noHistory="true" />
Plafker answered 7/12, 2010 at 12:32 Comment(14)
This is the best way to do it.Madrid
Equivalently you can use FLAG_ACTIVITY_NO_HISTORY.Goldenrod
How can I achieve this from code? Because I don't want to do this all the time. I would like to remove a given activity from history only under some conditions.Traumatism
Just be aware that using the noHistory attribute will make that activity finish, which might cause unexpected behavior with G+ login for example. See: #20384378 Took me a while to find this bug as my app kept crashing without any trace.Civet
using this, if u press home button and again start app, instead of resuming activity, it wl finish activity!Andraandrade
Thank you for the suggest.But this is just show the activity when the activity doesnt destroyed.it means, when the app or activity killed, after that, this not work.Breechloader
I have applied this attribute still is not working in-case of when app was not in recent app list. Any one please suggest how to remove activity when app was not in background previously.Oust
For more information please open this link. #31694070Oust
It is difficult to copy the needed flag as it is a link, so here one that can easily be copied. android:noHistory="true"Disassociate
Note: android:noHistory="true" will make it impossible to use things like the AccountPicker within the Activity; as when it opens your Activity will close.Adjournment
One problem. In new version of android M, when you call requestPermissions, your activity will disappears. This is a big problem ;)Lardner
what happens if I press back from B?Broker
Suppose we have four activities Checkout, Login, Otp, Payment. If user is already loged in then the flow will be Checkout --> Payment. But if user is not logged then the flow will be Checkout--> Login --> Otp --> Payment. In this case if user press back button from "Payment", user should directed to Checkout screen screen directly. Your answer works well in this situation. But what if user press back button on Otp screen, he must be directed to Login screen(this is the requirement). In this case your solution wiil not work because instead of Login user will directed to Checkout screen.Hedvig
This is not a good solution. It works fine when you get to Activity #3 - pressing Back closes the app. Pressing Back in Activity #2, however, should return you to #1 - but with this solution it just closes the app. Plus, as was already pointed out, when you for example request some permission on runtime, the Activity from which you were requesting it closes and doesn't reopen after the permission is granted/denied. I believe the OP's problem can't be solved statically by some Manifest value like this. It has to be done programmatically. Keep the backstack until you reach #3, then clear it.Simile
L
139

You can use forwarding to remove the previous activity from the activity stack while launching the next one. There's an example of this in the APIDemos, but basically all you're doing is calling finish() immediately after calling startActivity().

Lamb answered 14/12, 2009 at 4:20 Comment(9)
Hi Daniel, I read through the example, but that will only clear the history stack by 1 activity, won't it? If my stack looks like A, B, and I'm launching C, I want C to be the new root and completely clear A and B. In the sdk example, calling finish() from B would leave me with a stack of A, C, wouldn't it? Thanks.Disfigure
You could clear A as you launch B, and clear B as you launch C; however, I suppose then you wouldn't be able to back out from B to A if that's what you desire. I'll have to think on this more if that's a problem.Lamb
Mark, to achieve what you want, you have to use the flag: FLAG_ACTIVITY_CLEAR_TOP. I hope it helps.Alainaalaine
FLAG_ACTIVITY_CLEAR_TOP won't work because C isn't already in the back stack.Goldenrod
You made my day, i was looking for some way one time dialog between activities, so i needed to disable the dialog on back button. +1Lanneret
Yeah this is the method I use. I use complex custom dialogs and require to use the android:label="@string/activity_name_chat_add_dialog" the nohistory option cannot be used in my case for various reasons. Finish() works perfectly after calling startActivity()Usually
@DanielLew you can override onBackPressed() in B to start AZephan
@DanielLew There are so many examples in the APIDemos. You'd have the name of the example suggested ?Forcier
As @user8269411 mentioned, in some cases this should be just before startActivity()Dictatorship
D
55

Yes, have a look at Intent.FLAG_ACTIVITY_NO_HISTORY.

Decree answered 14/12, 2009 at 10:30 Comment(3)
Note that this sets no history for the activity you're launching to. To have no history for the activity you're launching from, I just set it android:noHistory="true" in the manifest.Lycanthrope
This work well. Use the intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) to set this flag.Haematozoon
@Lycanthrope this is useful when sometimes you want to keep it in history and at times you don't want it in history.Unilingual
W
25

This is likely not the ideal way to do it. If someone has a better way, I will be looking forward to implementing it. Here's how I accomplished this specific task with pre-version-11 sdk.

in each class you want to go away when it's clear time, you need to do this:

    ... interesting code stuff ...
    Intent i = new Intent(MyActivityThatNeedsToGo.this, NextActivity.class);
    startActivityForResult(i, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == R.string.unwind_stack_result_id) {
        this.setResult(R.string.unwind_stack_result_id);
        this.finish();
    }
}

then the one that needs to set off the chain of pops from the stack needs to just call this when you want to initiate it:

NextActivity.this.setResult(R.string.unwind_stack_result_id);
NextActivity.this.finish();

Then the activities aren't on the stack!
Remember folks, that you can start an activity, and then begin cleaning up behind it, execution does not follow a single (the ui) thread.

Wellmannered answered 13/5, 2011 at 3:4 Comment(2)
In case anyone comes across this later, I thought it may prove to be important to know, if you've rotated the screen, android will helpfully restart your application for you when you pop the last activity off of the stack. Just be aware of this!Wellmannered
This is a good answer if you only want to remove an activity from the stack conditionally depending on what the user does in the next activity +1Marasmus
E
23

One way that works pre API 11 is to start ActivityGameMain first, then in the onCreate of that Activity start your ActivitySplashScreen activity. The ActivityGameMain won't appear as you call startActivity too soon for the splash.

Then you can clear the stack when starting ActivityGameMain by setting these flags on the Intent:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

You also must add this to ActivitySplashScreen:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

So that pressing back on that activity doesn't go back to your ActivityGameMain.

I assume you don't want the splash screen to be gone back to either, to achieve this I suggest setting it to noHistory in your AndroidManifest.xml. Then put the goBackPressed code in your ActivitySplashScreenSignUp class instead.

However I have found a few ways to break this. Start another app from a notification while ActivitySplashScreenSignUp is shown and the back history is not reset.

The only real way around this is in API 11:

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Eyrir answered 8/3, 2012 at 18:48 Comment(0)
L
20

I use this way.

Intent i = new Intent(MyOldActivity.this, MyNewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(i);
Lusatian answered 15/9, 2015 at 1:32 Comment(1)
Thanks. I found this helpful in the case that there was a Home button in my menu, and I didn't want stacked activities to appear once user clicked home from there.Bulter
D
8

I know I'm late on this (it's been two years since the question was asked) but I accomplished this by intercepting the back button press. Rather than checking for specific activities, I just look at the count and if it's less than 3 it simply sends the app to the back (pausing the app and returning the user to whatever was running before launch). I check for less than three because I only have one intro screen. Also, I check the count because my app allows the user to navigate back to the home screen through the menu, so this allows them to back up through other screens like normal if there are activities other than the intro screen on the stack.

//We want the home screen to behave like the bottom of the activity stack so we do not return to the initial screen
//unless the application has been killed. Users can toggle the session mode with a menu item at all other times.
@Override
public void onBackPressed() {
    //Check the activity stack and see if it's more than two deep (initial screen and home screen)
    //If it's more than two deep, then let the app proccess the press
    ActivityManager am = (ActivityManager)this.getSystemService(Activity.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(3); //3 because we have to give it something. This is an arbitrary number
    int activityCount = tasks.get(0).numActivities;

    if (activityCount < 3)
    {
        moveTaskToBack(true);
    }
    else
    {
        super.onBackPressed();
    }
}
Denims answered 3/3, 2012 at 17:33 Comment(0)
I
8

In the manifest you can add:

android:noHistory="true"

<activity
android:name=".ActivityName"
android:noHistory="true" />

You can also call

finish()

immediately after calling startActivity(..)

Intermingle answered 8/2, 2017 at 11:2 Comment(1)
Better to use activity flags than put things in the manifest.Matildematin
D
6

Just set noHistory="true" in Manifest file. It makes activity being removed from the backstack.

Demetra answered 15/12, 2015 at 8:16 Comment(0)
F
4

It is crazy that no one has mentioned this elegant solution. This should be the accepted answer.

SplashActivity -> AuthActivity -> DashActivity

if (!sessionManager.isLoggedIn()) {
    Intent intent = new Intent(context, AuthActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    context.startActivity(intent);
    finish();
} else {
   Intent intent = new Intent(context, DashActivity.class);
   context.startActivity(intent);
    finish();
}

The key here is to use intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); for the intermediary Activity. Once that middle link is broken, the DashActivity will the first and last in the stack.

android:noHistory="true" is a bad solution, as it causes problems when relying on the Activity as a callback e.g onActivityResult. This is the recommended solution and should be accepted.

Fahlband answered 3/5, 2018 at 11:26 Comment(1)
That flag sounded too good to be true. FLAG_ACTIVITY_NO_HISTORY works nicely and as one would expect until one puts the app to background and then foreground again while having the activity with the flag on top of the stack. When going to background, the activity is destroyed. When returning to the app, one will see the previous activity from the stack. I definitely didn't want such behaviour.Twentyone
A
4

It's too late but hope it helps. Most of the answers are not pointing into the right direction. There are two simple flags for such thing.

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

From Android docs:

public static final int FLAG_ACTIVITY_CLEAR_TASK Added in API level 11

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

activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction with FLAG_ACTIVITY_NEW_TASK.

Aeneous answered 2/8, 2018 at 10:27 Comment(0)
P
2

Just call this.finish() before startActivity(intent) like this-

       Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
        this.finish();
        startActivity(intent);
Prehensile answered 28/9, 2017 at 9:23 Comment(1)
users who have error on "this", should change it to "ActivityOne.this"Dictatorship
W
1

Removing a activity from a History is done By setting the flag before the activity You Don't want

A->B->C->D

Suppose A,B,C and D are 4 Activities if you want to clear B and C then set flag

intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

In the activity A and B

Here is the code bit

Intent intent = new Intent(this,Activity_B.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Watery answered 24/12, 2019 at 9:14 Comment(0)
W
1
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            super.finishAndRemoveTask();
        }
        else {
            super.finish();
        }
Whitefish answered 12/5, 2020 at 5:16 Comment(0)
M
0

Here I have listed few ways to accomplish this task:

  1. Go to the manifest.xml- and put android:noHistory="true", to remove the activity from the stack.

  2. While switching from present activity to some other activity, in intent set flag as (Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK). It is demonstrated in the example below.

    Intent intent = new Intent(CurrentActivity.this, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(intent);here

Note :Putting the intent flags can cause blank screen for sometime (while switching activity).

Monophonic answered 13/9, 2022 at 13:52 Comment(0)
P
-7

Try this:

intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)

it is API Level 1, check the link.

Primine answered 22/3, 2013 at 11:43 Comment(2)
What is this supposed to do? Definitely doesn't solve the problem in question.Dithyramb
Are you sure you didn't mean Intent.FLAG_ACTIVITY_NO_HISTORY?Flattie

© 2022 - 2024 — McMap. All rights reserved.