Activity onNewIntent详解

onNewIntent() 的触发时间:

onNewIntent.png

  • 如图所示,onCreate() 和 onNewIntent() 不会被同时调用。

官方文档:

onNewIntent
·added in API level 1
·void onNewIntent (Intent intent)
·This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). 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.
·An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.
·Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.
·Parameters
intent Intent: The new intent that was started for the activity.

简单说明:

如果在 AndroidManifest.xml 中,将 Activity 的 launchMode 设置成了 "singleTop" 模式,或者在调用 startActivity(Intent) 时,设置了FLAG_ACTIVITY_SINGLE_TOP 标识,那么,当该 Activity 再次被启动时,如果它依然存在于 Activity 栈中,并且刚好处于栈的最顶层时,那么它将不会被重新创建,而是直接使用原来的实例,此时,onNewIntent(Intent) 将会被调用,后续生命周期中的其它方法,就可以使用 onNewIntent(Intent) 传递过来的新的 Intent 参数了。(也就是说,其它方法可以使用更新后的 Intent 参数)

也就是说,调用顺序如下:
onNewIntent() -> onRestart() -> onStart() -> onResume()

需要特别注意的是, 如果在 onNewIntent(Intent) 中,不调用 setIntent(Intent) 方法对 Intent 进行更新的话,那么之后在调用 getIntent() 方法时得到的依然是最初的值。

 

protected void onNewIntent(Intent intent) {
 
    super.onNewIntent(intent);
 
    setIntent(intent);//must store the new intent unless getIntent() will return the old one
 
    processExtraData();
 
}

在启动 Activtiy 时,如果希望在 onCreate() 不被触发的的情况下,依然可以对 Intent 进行操作,这就需要使用 onNewIntent()。
不要忘记,系统可能会随时杀掉后台运行的Activity,如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法.



作者:莫里亚蒂教授档案馆
链接:https://www.jianshu.com/p/aacf0ad54dca
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值