Determine if Activity came to front due to back navigation
android, android-activity, back, onresume
Solution
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();
}
Problem
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.