0

I have 3 activities: A, B and C.

From A I got to B and from A I go to C.

A --- B
|
|
C

When I return to A from this two activities, I press the back button.

From A, how can I know what activity was in the stack? How can I know if was B or C?

UPDATE - - I want to know how to know what activity press onBackPress(); I do not use startActivity from B or C;

Roland
  • 826
  • 2
  • 9
  • 24

3 Answers3

2

When starting activities A and C, use startActivityForResult(...) instead of the regular startActivity(...). You can create static integer variables for ACTIVITY_ID, ACTIVITY_B, and ACTIVITY_C. When your user backs out of either B or C, call setResult(...) with the corresponding ID variable. For more information about this method, see the developer doc on Activities: http://developer.android.com/reference/android/app/Activity.html

Nathan Walters
  • 4,116
  • 4
  • 23
  • 37
  • I want to know how to know this when in B and C was pressed onBackPressed(). I dont used startActivity(), only onBackPressed(). – Roland Jan 06 '14 at 18:03
  • In `onBackPressed(...)` call `setResult(...)`. Override `onActivityResult(...)` in activity A. Get the result there. – Nathan Walters Jan 06 '14 at 18:18
1

Start Activity B & C as startActivityForResult, use setResult method for sending data back From B/C and in A receive data as onActivityResult.

How to pass data from 2nd activity to 1st activity when pressed back? - android

Community
  • 1
  • 1
Yauraw Gadav
  • 1,706
  • 1
  • 18
  • 39
1

Just use Android's request codes with startActivityForResult(). In Activity A, call B or C with different request codes. First, define the codes:

private static final int ACTIVITY_B_REQUEST = 100;
private static final int ACTIVITY_C_REQUEST = 200;

Then start actvities.

B:

Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, ACTIVITY_B_REQUEST);

and C:

Intent intent = new Intent(this, ActivityC.class);
startActivityForResult(intent, ACTIVITY_C_REQUEST);

Then, still in your ActivityA, override onActivityResult() and check which request code has returned when back button was pressed:

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

    switch (requestCode) {
        case ACTIVITY_B_REQUEST:
            //returned from ActivityB
            break;

        case ACTIVITY_C_REQUEST:
            //returned from ActivityC
            break;

        default:
            break;        
    }
}

No need to pass anything from B or C - it's already taken care of by Android.

Melquiades
  • 8,496
  • 1
  • 31
  • 46