Search code examples
androidandroid-activitybackactivity-finish

How to finish activities up to one specific activity?


For example, I opened activities A, B, C, D.

I want to finish D and C and return back to B.

I don't want to open activity B with clear tasks and new task flags. I want to keep activity A too so user can return from B to A with back button.

How can I achieve this?


Solution

  • Intent intent = new Intent(getApplicationContext(), B.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    

    And in B activity:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }