1
votes

I use startActivity(Intent) to create a new activity in my Android application.

Is it possible to kill one of those activities and if yes how?

What I actually want to do is , lets say I have 4 activities at the same time running, opened in this sequence

Activity1 -> Activity2 -> Activity3 -> Activity4

When the user press the back button , instead of going

Activity4 -> Activity3 -> Activity2 -> Activity1 -> Close Application

I want it like this

Activity4 -> Activity1 -> Close Application

3
There are many ways to achieve this. Have you tried searching?Mert Akcakaya

3 Answers

1
votes

You could close Activity 2 and 3 with the finish() method when you start the next activity in the sequence. This will bring you from 4 to 1, but also from 3 to 1.

1
votes

Yes, you can do that.

Add this tag to Activity3 and Activity2 in your manifest:

android:noHistory="true"

This way those activities won't be added to the backStack, so pressing the back button on Activity4 would make the user go to Activity1. (Same would happen in Activity 3 and 2.)

1
votes

First Activity1 should have a special launchMode set in the manifest of singleTop. This will make sure another version of Activity1 will not be created if it already sits on top of the stack.

For each activity you want the special back button behavior you should override onBackPressed(). Inside onBackPressed implement the following code:

    public void onBackPressed () {
            Intent goBackTo1 = new Intent(this, Activity1.class);
            goBackTo1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(goBackTo1);
    }

The code above will start Activity1 but before it does it will clear all activities after Activity1 in the history stack. When this happens Activity1 will get a new intent delivered to the already running Activity1 in the method onNewIntent(Intent intent).

EX:

    Activity1->Activity2->Activity3->Activity4

Will become this when calling onBackPressed from 2,3 or 4 if they implement the code above. You might want to consider a base activity class as to not duplicate code.

    Activity1