再来看看应用-onNewIntent

前言

刚开始学的时候觉得intent很简单,后面逐渐被intent折磨。。。结合前面写过的文章,再来看看onNewIntent()回调时机:

 再看看接下来的分析,不对的话欢迎指正:

实例分析

 Activity 启动模式以及常见的启动Flag

先看这篇文章了解启动模式和flag,记得的话也可以不看。

  • 当Activity的LaunchMode为Standard时,由于每次启动Activity都是启动新的实例,和原来启动的没关系,所以不会调用原来Activity的onNewIntent方法;

  • 当启动模式为SingleTop时,Activity实例当前在栈顶时,此时会调用onNewIntent方法,调用顺序为:onCreate—>onStart—>onResume—>onPause—>onNewIntent—>onResume。

  • 当启动模式为SingleInstance和singleTask时,若Activity已在任务栈时,就会调用onNewIntent方法,调用顺序为:onPause—>onNewIntent—>onRestart—>onStart—>onResume。

所以,只有SingleTop(位于栈顶),SingleTask和SingleInstance(且栈中已存在实例),再次启动它们时才会调用,仅从后台切换到前台而不再次启动的情况下不会触发onNewIntent。
 

因此,当需要对intent携带的值做一些处理但是activity的启动模式不是standard的时候,可以在onNewIntent()回调里setIntent(intent),然后在onResume里处理。当然,也可以单独对onNewIntent(intent)传进来的intent处理。

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
}
 
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //must store the new intent unless getIntent() will return the old one
  setIntent(intent);
  processExtraData()
}

protected void onResume() {
  super.onResume();
  processExtraData();
}
 
private void processExtraData(){
  Intent intent = getIntent();
  //use the data received here
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值