Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if came back from child activity?

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?

like image 951
Vaibhav Mishra Avatar asked Nov 02 '11 14:11

Vaibhav Mishra


2 Answers

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.

like image 146
js- Avatar answered Oct 08 '22 08:10

js-


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.

like image 39
Muz Avatar answered Oct 08 '22 08:10

Muz