7

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.

SpeedBirdNine
  • 4,610
  • 11
  • 49
  • 67
Buda Gavril
  • 21,409
  • 40
  • 127
  • 196

4 Answers4

3

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().

Bruno Oliveira
  • 5,056
  • 18
  • 24
  • If I were doing it, I would go with something like this. – FoamyGuy Nov 04 '11 at 19:41
  • It's not ok to keep activities references in your applications because OS will not kill that activity while it has an reference. – Buda Gavril Nov 05 '11 at 11:59
  • This is different. Than my suggestion but this will only work if the activity started from the intent is the same as the running activity and not a new one. I don't know how that works when you call it with intents so can't answer without doing tests. Hope this made sense... – Warpzit Nov 05 '11 at 20:39
2

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.

1

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.

Damian
  • 8,062
  • 4
  • 42
  • 43
0

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...

Warpzit
  • 27,966
  • 19
  • 103
  • 155