How to detect if came back from child activity?

后端 未结 4 1080
南旧
南旧 2021-02-20 06:35

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?

4条回答
  •  执念已碎
    2021-02-20 06:54

    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.

提交回复
热议问题