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.
-
you can use action bar. on click of app icon navigate to home screen on click of back button in home screen exit back. – Raghunandan Aug 20 '13 at 19:08
-
1have a look here http://developer.android.com/design/patterns/navigation.html. – Raghunandan Aug 20 '13 at 19:18
-
http://stackoverflow.com/questions/2033914/quitting-an-application-is-that-frowned-upon/2034238#2034238 – CommonsWare Oct 19 '13 at 16:14
6 Answers
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!

- 13,637
- 10
- 47
- 54
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

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

- 4,064
- 6
- 39
- 69
-
This won't be any different from the default behavior of the back button – codeMagic Aug 20 '13 at 19:11
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().

- 9,166
- 3
- 34
- 52
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.

- 231
- 1
- 5
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.

- 2,277
- 1
- 27
- 25