[Android] 以singleInstance模式加载的Activity怎么接收以Bundle方式传递过来的参数 By onNewIntent() but not onResum

来源:互联网 发布:word2010表格数据缺失 编辑:程序博客网 时间:2024/05/29 17:20

问题来自这儿,Bundle在接收时未更新,http://blog.csdn.net/dadoneo/article/details/8164058。

虽然可以暂时解决问题,但并未说到根本原因,下面就Activity的LaunchMode来说说这个Bundle到底要怎么更新。

============================================

用如下方式打开Activity并传递参数

[java] view plaincopyprint?
  1. Intent i = new Intent(this, ImgInfo.class);   
  2. i.putExtra("id", mPhotoId);    
  3. startActivity(i);   
  4. Intent i = new Intent(this, ImgInfo.class);  
  5. i.putExtra("id", mPhotoId);   
  6. startActivity(i);  


如果不了解singleInstance的原理(之前并未注意到是这的问题),我们想当然地会在接收端Activity的onResume或其它方法中写下如下的代码:

[java] view plaincopyprint?
  1. Bundle bud = getIntent().getExtras();   
  2. if (bud != null && bud.containsKey("id")) {   
  3. mPhotoId = bud.getInt("id");   
  4. }    
  5. Bundle bud = getIntent().getExtras();  
  6. if (bud != null && bud.containsKey("id")) {  
  7. mPhotoId = bud.getInt("id");  
  8. }  


传递不同的id,你就会发现除了第一次能正确接收之外,其他的好像都不行了。其实就是没有更新,需要怎么做呢?

这时,我们需要重写接收端Activity的onNewIntent()方法,如下:

[java] view plaincopyprint?
  1. @Override  
  2. protected void onNewIntent(Intent intent) {    
  3.  super.onNewIntent(intent);  
  4.  setIntent(intent);  
  5.  InitArg();  
  6. }  


看看adnroid doc怎么说:

[java] view plaincopyprint?
  1. protected void onNewIntent (Intent intent)  
  2.   
  3. Added in API level 1  
  4. This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.  
  5.   
  6. An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.  
  7.   
  8. Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.  
  9.   
  10. Parameters  
  11. intent  The new intent that was started for the activity.  

其实就是:

onCreate是用来创建一个Activity也就是创建一个窗体,但一个Activty处于任务栈的顶端,若再次调用startActivity去创建它,则不会再次创建。若你想利用已有的Acivity去处理别的Intent时,你就可以利用onNewIntent来处理。在onNewIntent里面就会获得新的Intent.

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


这是为什么呢?这就需要深入了解Activity的LaunchMode了。下面的链接都介绍得很好:

http://marshal.easymorse.com/archives/2950



版权声明:http://blog.csdn.net/dadoneo/article/details/8170124

0 0
原创粉丝点击