startActivityForResult居然获取不到返回结果?

678 阅读1分钟

一、问题描述

startActivityForResult是开发中最常用来获取其他页面返回数据的一种方式,然后最近项目的一个页面中使用居然翻车,简直难以置信。于是打印onActivityResult()方法,resultCode怎么是RESULT_CANCELED,代码明明写的是RESULT_OK。检查代码发现语法没任何问题,接下来只能去看下源码中startActivityForResult()和setResult() 方法了。

二、分析源码

先看下startActivityForResult()的源码,在这个方法的注释说明似乎发现了什么:

    * <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 {@link Intent#FLAG_ACTIVITY_NEW_TASK}, it will not
    * run in your task and thus you will immediately receive a cancel result.

最后一句,大致意思就是不同栈的Activity通过startActivityForResult这种形式获取数据,会直接返回cancel 的结果。看到这里大概能知道问题的原因了,回到项目中检查Activity的launchMode,果然被设置成了SingleTask。

三、总结

不同栈的Activity通过startActivityForResult这种形式获取数据,会直接返回cancel的结果,页面需要返回result的需要谨慎设置launchMode。