Tuesday, August 25, 2015

onActivityResult called whenever the starting Activity instance is resumed

If Activity A starts another Activity B by calling the method startActivityForResult(...).

Whenever the same Activity A instance is resumed, the onActivityResult of A is called.

If Activity B starts a new instance of Activity A, then the onActivityResult(...) method is not call.

For example, if Activity B calls startActivity and start a new instance of Activity A on top of the task stack.
Intent startMainActivity = new Intent(this, MainActivity.class);
startActivity(startMainActivity);

The onActivityResult(...) is not called.

But if Activity B starts the same instance of Activity A by using the FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_SINGLE_TOP flags in the intent.

setResult(Activity.RESULT_OK);
Intent startMainActivity = new Intent(this, MainActivity.class);
startMainActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startMainActivity.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(startMainActivity);


Then the onActivityResult(...) is called.

However, the resultCode you passed in through method setResult(...) in Activity B will not be passed through Activity A if A is started by an Intent.

Although the onActivityResult(...) is called, but the resultCode is still 0 (RESULT_CANCELED)

Only if we finish Activity B and expose Activity A on to the top of task stack will pass the resultCode -1 (RESULT_OK) to onActivityResult(...) in Activity A.

setResult(Activity.RESULT_OK);
finish();


No comments:

Post a Comment