探究:IllegalStateException: Can not perform this action after onSaveInstanceState

最近撸代码时,向一个Activity中添加了几个fragment,用底部的RadioButton进行切换。发现了一个bug:当按下返回键退出程序以后,重新打开程序就会出现崩溃,崩溃之后再打开又正常。
logcat输出是这样的
描述
官方说明文档

public abstract int commitAllowingStateLoss ()

A transaction can only be committed with this method prior to its containing activity saving its state. If the commit is attempted after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored from its state. See commitAllowingStateLoss() for situations where it may be okay to lose the commit.

意思是在onSaveInstanceState()方法后调用commit(),就是抛出异常,这时建议使用commitAllowingStateLoss()。至于为什么返回键退出后的新程序,进行commit()还是会onSaveInstanceState()之后:
国外程序员的研究

修改后继续崩溃,继续研究》》
将onSaveInstanceState()方法清空:

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//      super.onSaveInstanceState(outState);
    }

崩溃依旧..国外的办法也没解决,继续》》
在网上搜索后,发现了一种新思路即绕过onSaveInstanceState()方法退出:

    @Override
    public void onBackPressed() {
        finish();
    }

不出所料还是血崩,将上述办法三合一,beng~ 继续》》
随后我想看看手机里成熟的app是怎么解决的,毕竟flagment应用的场景非常多。发现微博,贴吧,微信,QQ主界面都是在back以后回到桌面,并不退出程序,和home键类似。这应该是不想让用户方便的退出,让你随时回来继续浏览,我猜他们的实现方法是这样:

    public void onBackPressed() {
        moveTaskToBack(true); 
    }

这里设置为true是非root Activity(即首页面)也可用。只有淘宝是back后可直接退出,这是怎么实现的呢,一定有解决办法,而且上面四个app,在另外的页面是有退出程序按钮的,并且没有都没有bug。
于是我想到了用其他的退出方法

    public void onBackPressed() {
        System.exit(0);
    }

直接终止虚拟机,bug终于不见了。但是手机会有一瞬间黑屏,而淘宝退出时没有。我想应该是终止该程序虚拟机时手机会响应一段时间。于是继续码:先finish(),然后System.exit(0)》》》》》完美退出。

    public void onBackPressed() {
        finish();
        System.exit(0);
    }

Yes.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值