How to close 2 activities with single action

108 Views Asked by At

There are 3 activities A, B, C.

A -> B -> C with button

A <------ C with button that close C and B?

A -> B

   @Override
   public void onClick(View v) {
       Intent intent = new Intent(A.this, B.class);
       startActivity(intent);
   }

B -> C

   @Override
   public void onClick(View v) {
       Intent intent = new Intent(B.this, C.class);
       startActivity(intent);
   }

B -> A

   @Override
   public void onClick(View v) {
       finish();
   }

C -> B

   @Override
   public void onClick(View v) {
       finish();
   }

How to back to A from C with button that close C and B?

2

There are 2 best solutions below

0
AudioBubble On

Simply use finish() for this.

B -> C

@Override
public void onClick(View v) {

    Intent intent = new Intent(B.this, C.class);

    startActivity(intent);
    
    finish(); //Solution
}

Note: You can also use launch modes.

0
Hardik Hirpara On

Use startActivityForResult for A -> B and B -> C then override below method in C

override fun onBackPressed() {
    setResult(RESULT_OK)
    super.onBackPressed()
}

now in B override below method

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_CANCELED) return

        when (requestCode) {
            YoutIntentCodeWhenYouGoToC -> {
                setResult(RESULT_OK)
                onBackPressed()
            }
        }
    }

Now you are in A. And if you press a back button then it wont show B or C screen.