Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing the full Android activity stack on older SDKs (that lack FLAG_ACTIVITY_CLEAR_TASK)

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?

like image 943
Romain Avatar asked Mar 01 '11 12:03

Romain


1 Answers

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);

like image 166
Cristian Avatar answered Sep 24 '22 15:09

Cristian