调用startActivityForResult之后,onActivityResult立即响应

来源:互联网 发布:软考程序员有必要考吗 编辑:程序博客网 时间:2024/06/05 15:39

本文补充自:(PS:发现原因却不明白原理)

http://blog.csdn.net/u013807286/article/details/46044619

今天编码的时候,设计两个Activity之间的跳转,A->B,用了StartActivityForResult,为了用来判断是否请求然后刷新的,原本是可以正常刷新的,但是现在居然不行,有点莫名其妙,于是我在onActivityResult方法里打印log,发现只要一跳转到B界面,onActivityResult就执行了,为什么调用onActivityForResult之后,为什么onActivityResult立即响应?完全不符逻辑。查资料发现是与将要跳转的Activity的启动模式有关,特别是当启动模式为SingleTask的时候,不能使用onActivityResult函数,否则会立即调用onActivityResult函数。
如图:假设当前的应用程序存在两个栈:其中一个直接显示在屏幕上负责与用户完成交互,叫BackStack;另一个是隐藏在后台的background task,且位于该栈顶的Activity Y的启动模式被设置为
singleTask。
这里写图片描述
如果Activity 2中调用background Task中已经启动过的Activity Y,则background Task内占据屏幕并且将该Task下所有的栈保留当前的栈位置和顺序push进back Task形成新的结构。在Activity界面按返回键,则Activity Y出栈,Activity X占据屏幕。因此可见,由Activity2调用的Activity Y,但返回键后,回退显示的是Activity X。所以,即使在Activity执行setResult()函数,Activity2也是无法接收到的。

以上说的基本没问题.我需要补充说明的是
在Manifest文件中声明Activity的启动模式为singleTask并不会走如上流程而会走正常流程

测试表明,只有在跳转时用intent.addFlags(FLAG_ACTIVITY_NEW_TASK)才会走上述流程

流程为

这里写图片描述
看源码解释(直接Ctrl+左键点击就行)

/**     * If set, this activity will become the start of a new task on this     * history stack.  A task (from the activity that started it to the     * next task activity) defines an atomic group of activities that the     * user can move to.  Tasks can be moved to the foreground and background;     * all of the activities inside of a particular task always remain in     * the same order.  See     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back     * Stack</a> for more information about tasks.     *     * <p>This flag is generally used by activities that want     * to present a "launcher" style behavior: they give the user a list of     * separate things that can be done, which otherwise run completely     * independently of the activity launching them.     *     * <p>When using this flag, if a task is already running for the activity     * you are now starting, then a new activity will not be started; instead,     * the current task will simply be brought to the front of the screen with     * the state it was last in.  See {@link #FLAG_ACTIVITY_MULTIPLE_TASK} for a flag     * to disable this behavior.     * 别的没看懂,我看懂这一句了,说是startActivityForResult不能用这个flag     * <p>This flag can not be used when the caller is requesting a result from     * the activity being launched.     */    public static final int FLAG_ACTIVITY_NEW_TASK = 0x10000000;

官方都这么说了.就别做死了…(原因需要再研究一下..)

(PS:刚才已经编写完博客了,手贱不知道点击了什么(可能是连续点击了BackSpace或者是Delete当时手就在那个范围),竟然..把当前网页关了,以为会有缓存,可并没有/(ㄒoㄒ)/~~)

阅读全文
0 0