what is the right way to clear background activity/activites from stack?

Tal Kanel picture Tal Kanel · May 24, 2012 · Viewed 7.3k times · Source

as the questions title says - I need to know what is the best way to "remove"/destroy/finish an activity that are somewhere in the middle of stack and currently on pause mode (not specific instances - but specific derived classes).

for example:
if the current state of the stack looks like this:

ActivityD   <-- top of the stack, currently forground
ActivityC
ActivityA
ActivityC
ActivityA

a request to "clear" all ActivityC instances would cause the stack to be like:

ActivityD  <-- still top of the stack, currently forground.
ActivityA
ActivityA

I don't want to do that depends on activity launch mode or intent flags. I know how to use them and their benefits.

what I currently know I can do is to send broadcast which all activities needed to be destroyed would listen to, and call Activity.finish() when receive the broadcast.
that's working, but it requires receivers to be registered even when their hosting activity is paused, and I'm not sure "finish()" method been called from paused activity is something right to do.

is it right to call Activity.finish() method from resumed activity?

is it right to register receiver int the OnCreate() method, and unregister him OnDestroy()?

is it right to handle broadcast from resumed activity, and call finish() from that point?

is there an "Android way" or some API I don't know about to clear activities from stack?

thanks in advance

Answer

Awais Tariq picture Awais Tariq · May 25, 2012

Make a custom Broadcast receiver and register it in every activity which can be fired on event of your choice. in onReceiveMethod of every activity (may be selected )just call finish(). In this your activities will be removed from the stack. Further you can visit this for more help: On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activites