Android: Open Activity Without Save into the Stack

Android: open activity without save into the stack

When starting your list's Activity, set its Intent flags like so:

Intent i = new Intent(...); // Your list's Intent
i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NO_HISTORY); // Adds the FLAG_ACTIVITY_NO_HISTORY flag
startActivity(i);

The FLAG_ACTIVITY_NO_HISTORY flag keeps the new Activity from being added to the history stack.

NB: As @Sam points out, you can use i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); instead. There is no functional difference.

How to start an activity without calling another activity in Android?

I think at best what you can do is have two layouts in MainActivity, say MainLayout and LoginLayout, hide the MainLayout if the user is not logged in, and show LoginLayout in the same Activity, i.e. MainActivity, and make the user login, then again hide the LoginLayout and show the MainLayout. Or, rather than hiding the LoginLayout, restart the Activity.

Put these conditions at the start of onCreate() under if-else statements.

Somewhat like this (in your onCreate of MainActivity):

//Initially, have your LoginLayout GONE and MainLayout VISIBLE
if (!isUserLoggedIn) {
MainLayout.setVisibility(View.GONE);
LoginLayout.setVisibility(View.VISIBLE);
/*
Code to get user logged in,
then restart activity,
or simply hide LoginLayout and show MainLayout
*/
}

Clear the Backstack within an activity without using FLAG

@SorryForMyEnglish's answer is right. You just cannot to implement it. By using android:noHistory="boolean" attribute, see my concept maps below:

concept

Because of ActivityC and ActivityD (last activities) has a true value, so they cannot back to MainActivity, but they can back to ActivityA and ActivityB. Also, ActivityA and ActivityB can back to MainActivity. And the backstack is completely cleared without using this startActivity(intent) to open your next Activity (so you will need FLAG):

Intent intent = new Intent(CurrentActivity.this, NextActivityToBeOpened.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);

After you declared the value in manifest, you just need to call this startActivity(intent) to open the next Activity (no FLAG is needed):

startActivity(new Intent(CurrentActivity.this, NextActivityToBeOpened.class));

Is it very simple, right?

Remember:

  • Set your last Activity with android:noHistory="true" in manifest.
  • Another Activity must be set with false value.
  • Apply this attribute for all of your Activity.

As additional, here is how to use it inside your manifest:

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


Related Topics



Leave a reply



Submit