0

I have a application which have, let say, Activities A, B & C. B can be started by A as well as any other application's activity also. But C can only be started by B. On pressing back on C, user navigates to B(that is ok) but i have a button on C, which on pressing user should navigate to A or any other application's activity which launched B.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
Learner
  • 87
  • 1
  • 6

1 Answers1

0

To clear B off the stack and return to the previous Activity, do the following:

in C, launch B with an EXTRA:

Intent intent = new Intent(this, B.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("finish", true);
startActivity(intent);

Using CLEAR_TOP and SINGLE_TOP here ensure that this will go back to the existing instance of B, and not create a new one.

In B, override onNewIntent() as follows:

@Override
protected void onNewIntent(Intent intent) {
    if (intent.hasExtra("finished")) {
        // Wants to finish this Activity to return to the previous one
        finish();
    }
}

NOTE: This only works if B is still in the Activity stack when it launches C (ie: it doesn't call finish() when launching C).


An alternative would be to have B launch C using startActivityForResult(). In this case, C could return information (either in the resultCode or the returned Intent) that would allow B to determine if it should or should not finish.

David Wasser
  • 93,459
  • 16
  • 209
  • 274