Buda Gavril
Buda Gavril

Reputation: 21657

How to finish an activity from another activity

If Activity A is related to task T1 and Activity B is related to task T2, how can I finish Activity A from Activity B?

I need this because my application can be started from its shortcut or through notifications.

Upvotes: 7

Views: 4324

Answers (4)

user1325387
user1325387

Reputation:

I needed the same info and playing around with what yall stated here I came up with this.

 Intent intent = new Intent(MainActivity.this,HighScoresActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                        startActivity(intent);

Change the Activities to match your needs, but the FLAG_ACTIVITY_CLEAR_TOP removes the other activities from the stack.

Upvotes: 2

Damian
Damian

Reputation: 8072

Another alternative might be to call Activity B with the clear top flag from your notification handler e.g.

Intent intent = new Intent(context, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);       
context.startActivity(intent);

http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

Upvotes: 1

Bruno Oliveira
Bruno Oliveira

Reputation: 5076

While other approaches might work, the one that seems the most straightforward to me is sending an intent to the other activity that tells it to finish itself. That activity, upon receiving that intent, calls finish().

Upvotes: 3

EsbenG
EsbenG

Reputation: 28162

I'm not sure what would be the best approach, but one approach could be to pass Activity A to a singleton and fetch it from B and do a finish() on it...

Upvotes: 0

Related Questions