How to detect if came back from child activity?

后端 未结 4 999
南旧
南旧 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:50

    The method you're looking for may be the onResume method you can implements in your mother class ;). You must know that the onResume is also called the first time you launch any activity. Look at the lifecycle of an activity : http://developer.android.com/images/activity_lifecycle.png

    Regards,

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-20 07:08

    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.

    0 讨论(0)
  • 2021-02-20 07:12

    You can also override both the onBackPressed() method and the onOptionsItemSelected() method and put some logic there. For example I put this into my BaseActivity which all the other Activities extends from:

    @Override
    public void onBackPressed() {
        // your logic
        super.onBackPressed();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            // your logic
        }
        return super.onOptionsItemSelected(item);
    }
    
    0 讨论(0)
提交回复
热议问题