Search code examples
androidandroid-activityback-stack

Finish all Activities above certain Activity, but only if that certain Activity is on stack


I have to manage a situation: from current Activity (D) I have to kill all Activities above some certain Activity (X). I have to handle 2 cases:

  1. A - X - C - D
  2. A - B - C - D

As you can see in 1st situation X is on stack so after killing stack should look like: A - X.

In 2nd situation X is not on stack so stack should remain intact.

What I tried so far is : in D I send LocalBroadcastManager to "everywhere". I register for that LocalBroadcast in X only. So if X is on stack it'll receive LocalBroadcast and I try to kill "all Activities above myself" via:

    private BroadcastReceiver broadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent intents = new Intent(XActivity.this, XActivity.class);
            intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    };

But this fails with:

android.content.ActivityNotFoundException: No Activity found to handle Intent

Solution

  • Change your intent to intents :

    private BroadcastReceiver broadcast = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent intents = new Intent(XActivity.this, XActivity.class);
            intents.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intents);  //<-- here
        }
    };