您的位置:首页 > 移动开发 > Android开发

android onNewIntent

2013-12-11 21:23 162 查看
普通的Activity之间的跳转,如:新打开一个Activity,此时的执行顺序是0nCreat-onStart-onResume..,此时使用Intent 传递数据没有问题,在下个Activity 中直接getIntent().

但是如果是从A-B-A,且A 设置为singleTask 模式,则在B-A 时,实际执行的是onNewIntent- onResart-onStart-onResume.此时从B传递过来的intent,需要在onNewIntent() 中赋值给A的old Intent.这样你在getIntent() 时获取的才是B传回来的intent.

  当系统在低内存时,可能会杀掉A。此时,B-A 就是正常的0nCreat-onStart-onResume,此时的A的getIntent() 就是最新的从B传回来的,不经过onNewIntent().所以,所以从B返回的数据操作不能只是放在onNewIntent中,放在onStart 之后会比较安全。当然你也可以在Oncreat()和onNewIntent() 中都做处理。

在Android应用程序开发的时候,从一个Activity启动另一个Activity并传递一些数据到新的Activity上非常简单,但是当您需要让后台运行的Activity回到前台并传递一些数据可能就会存在一点点小问题。

首先,在默认情况下,当您通过Intent启到一个Activity的时候,就算已经存在一个相同的正在运行的Activity,系统都会创建一个新的Activity实例并显示出来。为了不让Activity实例化多次,我们需要通过在AndroidManifest.xml配置activity的加载方式(launchMode)以实现单任务模式,如下所示:

1 <activity android:label="@string/app_name" android:launchmode="singleTask"android:name="Activity1">

2 </activity>

launchMode为singleTask的时候,通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上,但这个时候,系统就不会再调用通常情况下我们处理请求数据的onCreate方法,而是调用onNewIntent方法,如下所示:

1 protected void onNewIntent(Intent intent) {

2   super.onNewIntent(intent);

3   setIntent(intent);//must store the new intent unless getIntent() will return the old one

4   processExtraData();

5 }

不要忘记,系统可能会随时杀掉后台运行的Activity,如果这一切发生,那么系统就会调用onCreate方法,而不调用onNewIntent方法,一个好的解决方法就是在onCreate和onNewIntent方法中调用同一个处理数据的方法,如下所示:

01 public void onCreate(Bundle savedInstanceState) {

02   super.onCreate(savedInstanceState);

03   setContentView(R.layout.main);

04   processExtraData();

05 }

06  

07 protected void onNewIntent(Intent intent) {

08   super.onNewIntent(intent);

09   setIntent(intent);//must store the new intent unless getIntent() will return the old one

10   processExtraData()

11 }

12  

13 private void processExtraData(){

14   Intent intent = getIntent();

15   //use the data received here

16 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android