onNewIntent
需要注意的是:
1、通过Intent启到一个Activity的时候,就算已经存在一个相同的正在运行的Activity,系统也会创建一个新的Activity实例。为了不让Activity实例化多次,我们需要通过在AndroidManifest.xml配置启动方式。
2、launchMode为singleTask的时候,通过Intent跳到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上,但这个时候----------系统就不会再调用onCreate方法,而是调用onNewIntent方法。
能用到的地方是A-->B-->C-->A,此时onActivityResult就有些复杂了。 例如:
1、点击 设置密码(A),跳到 设置密码页面(B),输入密码;
2、点击完成 跳到 确定密码页面(C),输入密码,设置成功后返回到设置页面(A)并带回一个状态,此时(A)中的“设置密码”变成“修改密码”;
3、用户设置过密码后,此页面就变成了“修改密码”的选项
4、C跳到A,这个A我们要用以前栈中已有的,不能再去新建一个A的实例,所以需要在AndroidManifest.xml配置activity的启动方式以实现单任务模式。每步的跳转中,我们不能finish掉上一步Activity,否则按返回键时,用户体验不好。。。。这时就需要onNewIntent了。当然这只是我的一个思路。
首先在AndroidManifest.xml配置activity的启动方式以实现单任务模式
先看第二个SecondActivity,它需要把值传到FirstActivity。
再来看FirstActivity
此时没有走onCreat方法,但是为了以防万一,最好在onCreat方法里也写上操作,因为后台运行的Activity可能在内存过高时被系统杀掉,这时就会走onCreat方法。
launchMode为singleTask的时候,通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上,但这个时候,系统就不会再调用通常情况下我们处理请求数据的onCreate方法,而是调用onNewIntent方法,如下所示:
protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent);//must store the new intent unless getIntent() will return the old one processExtraData(); }
不要忘记,系统可能会随时杀掉后台运行的Activity,如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法,如下所示:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); processExtraData(); } protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent);//must store the new intent unless getIntent() will return the old one processExtraData() } private void processExtraData(){ Intent intent = getIntent(); //use the data received here }