I've done qui a bit of reading and searching on SO, but can't find a way to clear the current activity stack. The context of my app is an activity started by a a background service / notification.
Imagine that my app allows you to organise a list of people. A few hours ago, you were viewing person X in the "View" activity, that's now the top of your stack. At some point in the future, the service triggers and I popup a new "Notify" activity for person Y. From there you can edit person Y's details.
When you finish this activity, it would be a confusing user experience to pop the stack and end up viewing person X. Ideally I'd like to go back to whatever the user was doing (email etc...), or at least to my app's home.
I tried starting "Notify" with FLAG_ACTIVTY_NEW_TASK
but开发者_运维技巧 that doesn't seem to help: when the task finishes it simply goes back to the previous task. What I want seems to be Android 3's new FLAG_ACTIVITY_CLEAR_TASK
, which doesn't exist in previous SDKs.
Does anyone have a suggestion to achieve that?
Just kill'em all!
You can achieve that by using BroadcastReceivers
:
- Create a
BaseActivity
like this:
public class BaseActivity extends GuiceActivity {
private KillReceiver mKillReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mKillReceiver = new KillReceiver();
registerReceiver(mKillReceiver,
IntentFilter.create("kill", "spartan!!!"));
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mKillReceiver);
}
private final class KillReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
}
- Make your activities extend that
BaseActivity
. - Whenever you want to clear the stack:
Intent intent = new Intent("kill");
intent.setType("spartan!!!");
sendBroadcast(intent);
If you already have an instance of your app's home running in the stack, when activity Y finishes you could start your app's home (using startActivity()
) with the flag FLAG_ACTIVITY_CLEAR_TOP
. As it's already on the stack, instead of creating a new instance of it, this would bring you back to your app's home and clear the stack on top of it.
Take a ArrayList and save all activities objects into arraylist in oncreate() of every activity. Whenever you want to finish particular activity ,just retrieve that activity instance from arraylist and finish that.
精彩评论