For Android, suppose 3 activities, a1 a2 a3, with their click hierarchy, a1->a2->a3.
My questions is in a2, how to detect it is from a3 by pressing the back key, instead of entering from a1?
You can determine if the activity is finishing by user choice (user chooses to exit by pressing back for example) using isFinishing() in onDestroy . @Override protected void onDestroy() { super. onDestroy(); if (isFinishing()) { // wrap stuff up } else { //It's an orientation change. } }
Android activities are stored in the activity stack. Going back to a previous activity could mean two things. You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
You can use onActivityResult
to check for return from another activity. Put this code within your a2 activity.
Declare the request code as a constant at the top of your activity:
public static final int OPEN_NEW_ACTIVITY = 123;
Put this where you start the new activity:
Intent intent = new Intent(this, NewActivity.class);
startActivityForResult(intent, OPEN_NEW_ACTIVITY);
Do something when the activity is finished. Documentation suggests that you use resultCode
, but depending on the situation, your result can either be RESULT_OK
or RESULT_CANCELED
when the button is pressed. So I would leave it out.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OPEN_NEW_ACTIVITY) {
// Execute your code on back here
// ....
}
}
You should take care to run onActivityResult
on the Activity itself, and not a Fragment.
You don't actually have to put any code in the a3 activity, but you can send data back if you like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With