23

I have an app with 3 activities.

I have the main activity. This calls the second activity, which then calls the third activity. I want return to the main activity without entering the onCreate.

This is the code for the third activity:

startActivity(new Intent(TerceraActiviry.this, Main.class));
andrewsi
  • 10,807
  • 132
  • 35
  • 51
Sárzena
  • 241
  • 1
  • 2
  • 4

4 Answers4

64

If your Activity is still running, this code will bring it to the front without entering onCreate

Intent openMainActivity = new Intent(TerceraActiviry.this, Main.class);
openMainActivity.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityIfNeeded(openMainActivity, 0);
ThePCWizard
  • 3,338
  • 2
  • 21
  • 32
4

in order to get back to previous Activity you have to finish the visible one, use this:

finish();

If the activity was started for a result, you should give a result then, like this:

Intent intent = new Intent();
intent.putExtra(KEY_RESPONSE, responseData);
setResult(RESULT_OK, intent);
finish();

And you should catch the result on the caller Activity using:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  switch (requestCode) {
    // Test for the code you have used to start the Activity
  }
}

Hope it helps, Regards

Spike777
  • 227
  • 5
  • 12
  • I found this finish() as the best option, if you are not planning to return to the current activity. Thanks! – Srini Jul 26 '20 at 17:48
1

You startActivityForResult instead of startActivity.

refer the android dev for more info here.

Gan
  • 1,349
  • 2
  • 10
  • 27
  • I don't agree - this will still create a new instance of the activity – kingraam Sep 13 '12 at 14:49
  • if you use startActivityForResult to start the second and third activities, you can return to the first activity by setting RESULT_OK and calling finish() method (respectively). There by passing control back to the already existing main activity. – Gan Sep 13 '12 at 14:59
  • Fair point - in the context of the question it looked like you were suggesting that he replace the startActivity with startActivityForResult, which wouldn't have helped – kingraam Sep 13 '12 at 15:02
  • Thats why i provided a link which gives a more detailed answer since its a very basic question. – Gan Sep 13 '12 at 15:04
1

The launch mode flag you want is clearTop. This will go back to the previous instance of the main activity and clear the second and third activity off the activity stack. For example, to do this from the code:

Intent intent = new Intent(TerceraActiviry.this, Main.class));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
kingraam
  • 1,521
  • 11
  • 18