androidandroid-intentandroid-activityback-stacktaskstackbuilder

Keep calling activity and clear other activities before that


I am calling activities in the following order A>B>C>D, now I want to call Activity A and clear B and C but keep D. I am calling A with Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP. But all the activities apart from A is getting cleared. Any body has any idea how to clear B and C and keep D>A.


Solution

  • You can move A to the top (from D) by doing this in D:

    Intent intent = new Intent(this, A.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(intent);
    

    There aren't any simple flags you can use to get rid of B and C. I would suggest that you have B and C register a BroadcastReceiver that listens for a specific ACTION. After you launch A from D, you can then send a broadcast Intent that will cause B and C to finish themselves. For example, in B and C do this:

    // Declare receiver as member variable
    BroadcastReceiver exitReceiver = new BroadcastReceiver() {
        @Override
        void onReceive (Context context, Intent intent) {
            // This Activity is no longer needed, finish it
            finish();
        }
    }
    

    in onCreate() register the receiver:

    registerReceiver(exitReceiver, new IntentFilter(ACTION_EXIT));
    

    don't forget to unregister the receiver in onDestroy()!

    In D, when you launch A, send a broadcast Intent containing ACTION_EXIT to make B and C finish, like this:

    sendBroadcast(new Intent(ACTION_EXIT));