当从后台唤醒activity时,getIntent() 无法获取到最新的值 或者为空

来源:互联网 发布:淘宝插件看别人数据 编辑:程序博客网 时间:2024/05/18 02:52

问题:做音乐项目遇到的问题,当我们的音乐播放器开启并后台运行后,点击其它地方的音频文件并选择我们的音乐播放器播放时,无法将包含这个音频文件信息的intent 传递过来。就是在用getIntent() 函数获取intent 时,发现获取的Intent中的信息为空。 (activity 的启动模式为 singTask)


问题分析: 用其他的启动模式时,不会出现这个问题,因为activity 重启了,但这不是我要的。我就要让Task 中的activity 只有这一个,so 问题很可能就出现在启动上,不同的启动模式它所走的方法也是不同的,所以就看一下singTask 启动模式在从后台唤醒时它的生命周期。

如果IntentActivity处于任务栈的顶端,也就是说之前打开过的Activity,现在处于
onPause
onStop 状态的话
其他应用再发送Intent的话,执行顺序为:

onNewIntent
onRestart
onStart
onResume 

可以看到第一步先走的是 onNewIntent ,所以我就查了一下 onNewIntent 方法,发现

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

}
复制代码

0 0
原创粉丝点击