14

I'd like to know if my Activity was displayed because the user pressed back on some other Activity. In the Lifecycle I couldn't identify any Callbacks that are robustly giving me that info.

onRestart() is not working. It will also fire if the Apps Task was brought to front. onResume() will not work for the same reason.

I suppose there is a simple solution for that, but in Android supposedly simple things can be pretty nasty.

Jakob
  • 1,126
  • 3
  • 16
  • 38

1 Answers1

18

Call your 2nd activity with startActivityForResult(Intent, int), then override the onBackPressed() in the 2nd activity and have it setResult() to RESULT_CANCELED. Lastly, have the 1st activity catch that in onActivityResult().

Code example:

Activity 1:

Intent i = new Intent(Activity1.this, Activity2.class);
startActivityForResult(i, 0);

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

    if (requestCode == 0) {
        if (resultCode == RESULT_CANCELED) {
                // user pressed back from 2nd activity to go to 1st activity. code here
        }
    }
}

Activity 2:

@Override
public void onBackPressed() {
    setResult(RESULT_CANCELED);
    finish();
}
Mxyk
  • 10,678
  • 16
  • 57
  • 76
  • 2
    good answer, though I have around 15 Activities and I am using AndoridAnnotations which has no option for calling startActivityForResult (yet, though in an upcoming release)... so I am still hoping for some other idea... – Jakob Aug 28 '12 at 12:09
  • 1
    Does AndroidAnnotations prevent you from using normal, basic Android constructs like this one? I wouldn't use such a tool then... – Ridcully Aug 28 '12 at 12:19
  • 1
    No I can use standard android constructs, but I already have 15 Activities that i have to touch now. The answer might just be "the way to do it". – Jakob Aug 28 '12 at 12:22
  • If the user presses back, the result code passed in to onActivityResult() will NOT be RESULT_OK (unless you do some other monkeying around). You don't need to touch any of the 15 callable activities - just test for (resultCode != RESULT_OK). – tbm Jan 20 '15 at 15:33