我们知道,startActivity
方法将被调用startActivityForResult
方法;还有一些如下代码:
/**
* Same as calling {@link #startActivityForResult(Intent, int, Bundle)}
* with no options.
*
* @param intent The intent to start.
* @param requestCode If >= 0, this code will be returned in
* onActivityResult() when the activity exits.
*
* @throws android.content.ActivityNotFoundException
*
* @see #startActivity
*/
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
我会尽力找到处理requestCode的源代码。但是我什么也没找到。有人可以复制源代码并告诉我仅在requestCode> = 0OnActivityResult()被调用时如何处理吗?
答案 0 :(得分:1)
如您所包含的代码片段所示,startActivityForResult
的两个参数版本调用了startActivityForResult
的三个参数版本。三参数版本looks like this:
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
if (mParent == null) {
//...
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
//...
} else {
//...
}
}
if (requestCode >= 0) {}
块中的注释描述了当请求代码为>= 0
与< 0
时行为如何变化。
如果我们查看the source code for mInstrumentation.execStartActivity
,则会发现以下内容:
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//...
if (am.isBlocking()) {
return requestCode >= 0 ? am.getResult() : null;
}
// ...
}
如果return requestCode >= 0 ? am.getResult() : null;
为负,则行null
返回ActivityResult
requestCode
。回到该答案顶部的startActivityForResult
代码,我们看到mMainThread.sendActivityResult
被调用,当且仅当ActivityResult
返回的execStartActivity
是非{{1 }}。最终导致调用null
的是sendActivityResult
。因此,这里的逻辑路径是:
onActivityResult
以负数startActivityForResult
调用
called requestCode
以负数mInstrumentation.execStartActivity
调用
↳requestCode
返回mInstrumentation.execStartActivity
called null
不被称为
called mMainThread.sendActivityResult
没有被叫