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
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
I also had the same problem. What I did is, I kept a static array list, and whenever I used to go from one activity to another, in the onCreate() method of new activity, I added the object of current activity into that list like this:
SomeClass.addActivity(CurrentActivity.this);
I added the above statement in each activity.
The addActivity():
public void addActivity(final Activity activity) {
activityList.add(activity);
}
And when I wanted to clear the stack, I called:
public boolean clearStack() {
for (Activity activity : activityList) {
activity.finish();
}
activityList.clear();
return (activityList.isEmpty());
}
In this way, I cleared my activity stack.
Thank you :)
Intent myintent = new Intent(YourCurrentActivity.this, YourNextActivitys.class);
myintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);
finish();
I think this is the right way to clear all previous activities...
来源:https://stackoverflow.com/questions/10736594/what-is-the-right-way-to-clear-background-activity-activites-from-stack