Start Android Activity Without History

Posted by Grego on October 23, 2017

How

To avoid adding an activity to the history stack, when creating the intent for that activity simple set the Intent.FLAG_ACTIVITY_NO_HISTORY flag like so:

final Intent someActivityIntent = new Intent(/* insert required parameters here */);
someActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

Then start your activity normally:

startActivity(someActivityIntent);

Sample Use Cases

Now why might we want to do this?

The other day I was working on adding a tour screen flow to one of my Android apps. Unlike iOS, Android has an integrated back button. This means we need to be more conscious about our Activity history stack. To keep the flow consistent with the App’s iOS counterpart I decided we should not be able to go back to the tour once it has been finished.

Since I typically use a factory method for creating my intents my code looks something like this:

public class TourActivity extends AppCompatActivity {

    // some field declarations here removed for brevity

    public static Intent createIntent(@NonNull final Context context) {
        final Intent tourIntent = new Intent(context, TourActivity.class);
        tourIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        return tourIntent;
    }

    // other activity code here...
}