Search code examples
androidandroid-activity

Can I finish 2 activities using backpress


I call B Activity on A Activity. But B Activity background is transparent. So I can't use INTENT_FLAG. A activity have to remain.

So!

When I press back button How to finish 2 Activities together? Not Using INTENT_FLAG.


Solution

  • I would suggest to start your second activity for result from the first activity as following:

    Intent intent = new Intent(this, SecondActivity.class);
    startActivityForResult(intent, 1);
    

    Then, in your SecondActivity override onBackPressed

    @Override
    public void onBackPressed() {
        Intent returnIntent = new Intent();
        setResult(Activity.RESULT_CANCELED, returnIntent);
        finish();
    }
    

    And in your FirstActivity:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
        if (requestCode == 1 && resultCode == Activity.RESULT_CANCELED) {
            finish();
        }
    }