onNewIntent是个什么东西?

来源:互联网 发布:91助手苹果mac版下载 编辑:程序博客网 时间:2024/04/26 03:54

Android API
很奇怪,谷歌没有在官方文档中说明这个方法
这里写图片描述
天无绝人之路,我们在源码中找到了这个方法
这里写图片描述

In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
翻译:
在任何情况下,当Activty位于栈顶并将被重新启动时,不会新创建一个新的实例,取而代之的是使用去重新启动的intent调用已经存在的实例中onNewIntent方法

谷歌的开发人员,我得吐槽一下,非要把这么重要的一句话放在singleTop后面,很容易让人以为必须设置singleTop才能调用onNewIntent方法,其实不是这样的!!!singleTask清除目标Activity上面的所有Activity,那目标不就是位于栈顶?singleInstance拥有一个独立的任务栈,所以也是位于栈顶的!

接下来我们出道题来思考下:

A和B的启动模式都是singleTask,并且AB均重写了onNewIntent方法,A方法里面是输出onNewIntent1,B方法里面是输出onNewIntent2,然后A启动B,B启动A,如此循环,问输出结果是什么?

答案是一直输出onNewIntent1,这是为什么呢?
1 启动A 因为A才创建于栈中,不会调用onNewIntent
2 启动B 因为B也是刚创建,所以也不会调用onNewIntent
3 启动A 因为设置的是singleTask模式,并且A已经存在,所以要把A上面的B清空,A就位于栈顶了,这个时候满足栈顶+已经存在,所以A调用方法输出onNewIntent1
4 启动B 因为B被清空,所以再次创建B,所以不会调用onNewIntent
5678….

弄明白了onNewIntent,我们再来理解一下四种启动模式:

standard 每次创建都是一个新的activity,谈不上已经存在,因为每次都是新的

singleTop

singleTop 如果栈顶是该activity就复用,不然的话就重新创建

singleTask

singleTask 如果栈中存在该activity,那么就把这个activity上面的所有activity都清空,让该activity位于栈顶,否则的话就创建

singleInstance

singleInstance 如果有该activity的话就复用,否则的话就新建一个栈并且就栈内就该activity一个activity,也是位于栈顶