Activity设置为启动模式为singletask第二次进入activity getintent获取不到问题

现在假设我们有Activity A ,B
activity singletask 启动模式 当此activity存在栈中 再次进入无需重新创建移除其上面的activity使其到栈顶 取用
当B的启动模式设置为singletask第一次A->B getintent 可以获取到数据,当第二次进入的时候突然获取不到了 数据是空的,为什么会这样呢,先看下上面关于singletask的介绍,我们在看下源码里面getintent方法的介绍

 /**返回开始创建的activity的意图*/
 /** Return the intent that started this activity. */
    public Intent getIntent() {
        return mIntent;
    }

就是说通过getIntent获取到的是activity创建时候的意图intent,并且会把这个意图保存下来,之后如果在activity从后台调出到前台,用getIntent方法获取到的始终是之前保存的意图。
那当我们的意图发生变化的时候怎么办呢
activity的源码中紧邻着getIntent的还有个setIntent方法

 /** 
     * Change the intent returned by {@link #getIntent}.  This holds a 
     * reference to the given intent; it does not copy it.  Often used in 
     * conjunction with {@link #onNewIntent}. 
     *  
     * @param newIntent The new Intent object to return from getIntent 
     * 
     * @see #getIntent
     * @see #onNewIntent
     */ 
    public void setIntent(Intent newIntent) {
        mIntent = newIntent;
    }

注释上说 可以通过此方法改变getintent返回的intent 经常与onNewIntent方法一起使用
好那我们在看一下onNewIntent的源码注释(渣翻译见谅)

 /**
     * This is called for activities that set launchMode to "singleTop" in
     * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP}
     * flag when calling {@link #startActivity}.  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. 
     *  
     * <p>An activity will always be paused before receiving a new intent, so 
     * you can count on {@link #onResume} being called after this method. 
     * 
     * <p>Note that {@link #getIntent} still returns the original Intent.  You 
     * can use {@link #setIntent} to update it to this new Intent. 
     * 
     * @param intent The new intent that was started for the activity. 
     *  
     * @see #getIntent
     * @see #setIntent 
     * @see #onResume 
     */
    protected void onNewIntent(Intent intent) {
    }

大概的意思就是activity设置为singletop的时候在栈中当startactivity()通过Intent启到一个Activity,如果系统已经存在一个实例,系统就会将请求发送到这个实例上不会重新创建。
getintent返回之前的intent可以通过setintent改变返回的intent。此方法会在onresume之前调用
解决方法
所以当我们获取不到数据的时候只要重写onNewIntent就好

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        setIntent(intent);
        super.onNewIntent(intent);
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值