Activity setResult 和 finish

有个问题: setResultfinish 的调用顺序关系, 是先调用 setResult 还是先调用 finish, 还是两者的调用顺序无所谓呢? 最直接的就是看看源码找答案.

先看 setResult

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}
}

调用 setResult 时, 会将 resultCoderesultData 赋给 Activity 的成员变量中.

再看 finish

1
2
3
public void finish() {
finish(DONT_FINISH_TASK_WITH_ACTIVITY);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 (ActivityManager.getService().finishActivity(mToken, resultCode, resultData, finishTask)) {
mFinished = true;
}
} catch (RemoteException e) {
// Empty
}
} else {
mParent.finishFromChild(this);
}
...
}

在调用 finish 时, 会将 Activity 中的成员变量 mResultCode mResultData 传递到 ActivityManagerfinishActivity 中.

结论

如果要设置 resultCoderesultData, 则必须要在 finish 之前调用 setResult, 将 resultCoderesultData 存入 Activity 的成员变量中.