setResult()->finish()
setResult()必须保证在finish()之前执行,否则返回码设置失效,为默认值0。
要搞懂原因,必须先回到源码中:
// protected by synchronized (this)
int mResultCode = RESULT_CANCELED;
Intent mResultData = null;
/*省略部分代码*/
public final void setResult(int resultCode) {
synchronized (this) {
mResultCode = resultCode;
mResultData = null;
}
}
public final void setResult(int resultCode, Intent data) {
synchronized (this) {
mResultCode = resultCode;
mResultData = data;
}
}
/*省略部分代码*/
public void finish() {
finish(DONT_FINISH_TASK_WITH_ACTIVITY);
}
/*省略部分代码*/
private void finish(int finishTask) {
if (mParent == null) {
int resultCode;
Intent resultData;
synchronized (this) {
resultCode = mResultCode;
resultData = mResultData;
}
if (false) Log.v(TAG, "Finishing self: token=" + mToken);
try {
if (resultData != null) {
resultData.prepareToLeaveProcess(this);
}
if (ActivityManagerNative.getDefault()
.finishActivity(mToken, resultCode, resultData, finishTask)) {
mFinished = true;
}
} catch (RemoteException e) {
// Empty
}
} else {
mParent.finishFromChild(this);
}
}
可以发现setResult()只是给 mResultCode 和 mResultData 赋值,finish()将mResultCode 和 mResultData传给了native层。所以setResult()必须保证在finish()之前执行,否则返回码设置失效,为默认值0。