Pritam
Pritam

Reputation: 2507

Finish any previous activity in stack from current activity?

How to finish any previous activity in application stack (at any level , I mean not immediate parent) , from current activity like on some particular event I want to invalidate this previous activity? Any help ? Thanks.

Upvotes: 13

Views: 18013

Answers (4)

Ryan
Ryan

Reputation: 882

I know this answer may be late, but I'm still going to post it in case someone is looking for something like this.

What I did is I declared a static handler in in ACTIVITY_A

public static Handler h;

and in my onCreate() method for ACTIVITY_A, I have

h = new Handler() {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch(msg.what) {

            case 0:
                ACTIVITY_A = null;
                finish();
                break;

            }
        }
        
    };

Now, from any activity after this one, such as ACTIVITY_B, or ACTIVITY_C I can call

ACTIVITY_A.h.sendEmptyMessage(0);

which then calls finish() in ACTIVITY_A and ta-da! ACTIVITY_A is finished from a different activity.

Upvotes: 33

narancs
narancs

Reputation: 5294

So I tired this, but didn't work after I did more deeper testing (I leave it here for future reference): android:clearTaskOnLaunch

Suppose, for example, that someone launches activity P from the home screen, and from there goes to activity Q. The user next presses Home, and then returns to activity P. Normally, the user would see activity Q, since that is what they were last doing in P's task. However, if P set this flag to "true", all of the activities on top of it (Q in this case) were removed when the user pressed Home and the task went to the background. So the user sees only P when returning to the task.

https://developer.android.com/guide/topics/manifest/activity-element.html

UPDATE This did work

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

Upvotes: 6

Pritam
Pritam

Reputation: 2507

This may be possible by using static variables. Like use a boolean variable activity_name_dirty = false; mark this as true as soon as your condition of invalidating that particular activity occurs. So any time later when calling this activity have a check on the state of activity_name_dirty. You may then use Activity Flags to create a new instant as described in Activity Fundamentals

Upvotes: 2

Steve Haley
Steve Haley

Reputation: 55714

You can use the Intent flag FLAG_ACTIVITY_CLEAR_TOP to restart an activity from the stack and clear everything that was above it. This isn't quite what you're asking, but it might help.

To do this, use:

Intent intent = new Intent(context, classToBeStarted.class);
intent.setFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Upvotes: 4

Related Questions