How can I detect if an activity came to focus after pressing the back button from a child activity, and how can I execute some code at that time?
One possibility would be to start your child activity with startActivityForResult()
and implement onActivityResult()
which will be called when you return from the child activity.
js's answer is right, but here is some debugged code.
Declare the request code as a constant at the top of your activity:
public static final int OPEN_NEW_ACTIVITY = 12345;
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
// ....
}
}
For some reason, I had trouble when putting this in a Fragment. So you will have to put it in the Activity.
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