最近研究启动模式,顺便查看了一下startActivity和startActivityForResult的源码:
最后发现startActivity最后也是调用
public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) ;这个方法的。
我们来看看这个方法(sdk23):
* Launch an activity for which you would like a result when it finished. * When this activity exits, your * onActivityResult() method will be called with the given requestCode. * Using a negative requestCode is the same as calling * {@link #startActivity} (the activity is not launched as a sub-activity). * * <p>Note that this method should only be used with Intent protocols * that are defined to return a result. In other protocols (such as * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may * not get the result when you expect. For example, if the activity you * are launching uses the singleTask launch mode, it will not run in your * task and thus you will immediately receive a cancel result. * public void startActivityForResult(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; } cancelInputsAndStartExitTransition(options); // TODO Consider clearing/flushing other event sources and events for child windows. } else { if (options != null) { mParent.startActivityFromChild(this, intent, requestCode, options); } else { // Note we want to go through this method for compatibility with // existing applications that may have overridden it. mParent.startActivityFromChild(this, intent, requestCode); } } }分析:从它的注释中我们可以知道两点:
1)这个方法的请求码参数分为>=0和<0两种情况,startActivity方法中调用这个方法时使用的就是-1,如果直接调用这个方法并且
请求码传值为负数就相当于是调用startActivity,不会有onActivityResult方法的回调。前者启动的activity是当前activity的
子activity,后者启动的activity则不是。
2)使用这个方法时传的Intent的协议需要是属于等待返回一个结果的,如果是其他不需要返回结果的,
比如:@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may not get the result when you expect。
当然,这里有个例子:比如使用这个方法准备启动的activity的启动模式是singleTask,你将会直接接受到一个表示取消的返回结果。
最后推荐一篇非常不错的博客,这篇博客刚刚好解决了我研究activity启动代码时遇到的瓶颈!点击打开链接