问题
I have three activities A, B and C.
A starts B with startActivityForResult(getIntent(), ACTIVITY_B);
and B starts C with startActivityForResult(getIntent(), ACTIVITY_C);
. ACTIVITY_B
and ACTIVITY_C
are constants with same value across activities.
When C returns with RESULT_OK, then B is restarted with the code:
if (resultCode == Activity.RESULT_OK){
finish();
startActivityForResult(getIntent(), ACTIVITY_B);
}
This works fine.
When B has to return (on clicking a menu item), it sets the activity result.
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case MENU_CONFIRM:
System.out.println("Setting Result to RESULT_OK");
setResult(Activity.RESULT_OK);
finish();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
However I can see that the setResult(Activity.RESULT_OK);
is ignored because it is always received as RESULT_CANCEL
in the Activity A (onActivityResult
). I'm using 2.3.
Any clues?
回答1:
Don't finish B and start a new one, A will not get notified because it's not the B it opened. Instead, if C needs to return something to B when it ends, create an Intent, put your result values on it, and check this result in B:
C:
Intent data = new Intent();
// Store values you want to return on the intent
setResult(RESULT_OK, data);
finish();
B: in onActivityResult
if (resultCode == Activity.RESULT_OK) {
// get values from the intent and change B accordingly
}
回答2:
I am curious how you are handling your Intents and Activity lifecycle.
From what I have read in both of your posts:
- A starts B with startActivityForResult().
- B starts C with startActivityForResult().
- C completes its task, calls setResult() and finish().
Now unless there is something I am missing, Activity B uses this code:
if (resultCode == Activity.RESULT_OK){
finish();
startActivityForResult(getIntent(), ACTIVITY_B);
}
to start itself? Could you clarify this?
Addition
I believe you are starting B from B so when you call setResult() and finish() in your second instance of B you are returning to the first B Activity.
If you are not using any special Intent flags the lifecycle will be:
- A starts B
- B starts C
- C finishes
- B resumes automatically, B finishes
- B starts C
- A resumes automatically.
From what I understand you have altered that cycle to:
A starts B
- B starts C
- C finishes
- B resumes automatically, onActivityResult() starts 2nd B
- 2nd B finishes, (You expect to see A next, however...)
- B resumes automatically (If you call finish() again you should see A at this point).
...
- B starts C
- A is waiting in the stack to be resumed.
来源:https://stackoverflow.com/questions/11043239/setresult-does-not-work-after-activitiy-is-restarted