1

My project has 4 activities and users from activity A go to B after that to C and D. I need to create a button in activity D to close program directly because if user has to close all activities ( D ->C -> B -> A-> close) it would be unfriendly.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Aminika
  • 143
  • 1
  • 7

6 Answers6

2

Register a broadcast receiver in each of the activities, listening for the "close all action", when the button in the last activity is pressed, send that broadcast, so all the activities register will execute their "onReceive" method on the broadcastreceiver, and there all them will be finished as long as they are registered. This will definitely do the trick, although to be honest is quiet a poor implementation, chances that you are doing something wrong in the navigation are high, maybe fragments or a tab would be better suited for what you are trying, in stead of creating such a stack of activities...

Hope this helps...

Regards!

Martin Cazares
  • 13,637
  • 10
  • 47
  • 54
2

I think onActivityResult could be the better option.You could finish the activity if required task is being completed otherwise just backtrack on previous activity

Aditya Rai
  • 139
  • 8
0

You should override onBackPressed() from each Activity and call finish().

Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
0

Assume the first activity in your application is named ActivityMain. Presumably it will be the oldest one on the stack.

Create an intent to start ActivityMain using the flag FLAG_ACTIVITY_CLEAR_TOP. Set an extra in that intent to indicate this is an application exit, and call startActivity() with that intent. This will clear the stack and get you back to Activity main.

In ActivityMain call getIntent() then check for the exiting application Extra value. If it is set, call finish().

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52
0

A not so elegant solution:

Instead of calling startActivity, call startActivityForResult, from A to D.

On Activity D, when your button is pressed, set any result (let's say Activity.RESULT_OK) and call finish().

On each Activity (from A to C), override the method onActivityResult to check for the result. If the result is Activity.RESULT_OK, then you set the same result and call finish() again.

If you want, instead of just setting the result, add an Intent with some flag to tell the previous Activities to finish themselves.

0

Simply do one thing . In your activities add an overriden method onPause

onPause(){
finish();
}

This will close all your activities once you press back from any activity.

Udit Kapahi
  • 2,277
  • 1
  • 27
  • 25