Search code examples
androidandroid-lifecycleonresume

Two activities and different case for onResume method


My problem is I have two activities A and B, and 1 function in the acitivity B.

In activity A , if I click on a button it will call : this.finish(), then I will be in the second activity i.e. ActivityB and with theonResume() it will execute my function B : onResume() { functionB}

The thing i want to use functionB after this case. So I wonder if it's possible to know (when using onResume()) , from "where you come" : So If i get onResume() from another activity that is not A, It would never use function B, but It will use only B if I finish ActivityA

Hope you understand.

Thank you


Solution

  • This can be accomplished with startActivityForResult instead of startActivity. Like so:

    startActivityForResult(activityIntent, 100);
    

    Then instead of calling this.finish() you would call:

    setResult(RESULT_OK);
    this.finish();
    

    Then in your resuming Activity this method will get called before onResume:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 100) {
            // do something 
        }
    }
    

    Here you can set some kind of boolean variable to true to let the Activity know that it has come from your other Activity then in onResume check to see if the boolean is set to true, if it is do whatever you wish.