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


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

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

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

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

    Intent i = new Intent(this, ImgInfo.class); 
    i.putExtra("id", mPhotoId);  
    startActivity(i); 
    Intent i = new Intent(this, ImgInfo.class);
    i.putExtra("id", mPhotoId); 
    startActivity(i);


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

    Bundle bud = getIntent().getExtras(); 
    if (bud != null && bud.containsKey("id")) { 
    mPhotoId = bud.getInt("id"); 
    }  
    Bundle bud = getIntent().getExtras();
    if (bud != null && bud.containsKey("id")) {
    mPhotoId = bud.getInt("id");
    }


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

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

     @Override
     protected void onNewIntent(Intent intent) {  
      super.onNewIntent(intent);
      setIntent(intent);
      InitArg();
     }


    看看adnroid doc怎么说:

    protected void onNewIntent (Intent intent)
    
    Added in API level 1
    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.
    
    An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.
    
    Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.
    
    Parameters
    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



    Meet so Meet. C plusplus I-PLUS....
  • 相关阅读:
    JSON.NET C# 类库
    javascript绑定事件,JQuery绑定事件
    C#批量上传图片
    关闭或重启Windows Server 操作系统时,系统会弹出一个提示窗口
    Asp.net组织结构图控件,思维导图控件
    C# 判断是否可以连接服务器?
    javascript获取select,checkbox,radio的值
    IE、FF、Safari、OP不同浏览器兼容报告
    Microsoft Windows Server 2008 Standard Edition激活码申请方法
    自动修改电脑IP地址.bat
  • 原文地址:https://www.cnblogs.com/iplus/p/4467364.html
Copyright © 2020-2023  润新知