前言
刚开始学的时候觉得intent很简单,后面逐渐被intent折磨。。。结合前面写过的文章,再来看看onNewIntent()回调时机:
再看看接下来的分析,不对的话欢迎指正:
实例分析
先看这篇文章了解启动模式和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
}