Android 关于Activity中存储数据的问题

程序异常退出onSaveInstanceState()

一:怎么用(注意后面的参数)
onSaveInstanceState()方法保存数据

  @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(TAG, 123);
        Log.i(TAG, "onSaveInstanceState: ");
     //   super.onSaveInstanceState(outState, outPersistentState);
        super.onSaveInstanceState(outState);
    }

然后在onCreate中取到数据用的是Bundle

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ");
        setContentView(R.layout.activity_main);
        tv=(TextView) findViewById(R.id.tv);

        if(savedInstanceState!=null&&savedInstanceState.getInt(TAG)!=0){
            int a=savedInstanceState.getInt(TAG);
            tv.setText("baocunde"+a);
        }else{
            tv.setText("现在没有存储的数据");
        }


    }

二:什么时候调用
1、当用户按下HOME键时。
这是显而易见的,系统不知道你按下HOME后要运行多少其他的程序,自然也不知道activity A是否会被销毁,故系统会调用onSaveInstanceState,让用户有机会保存某些非永久性的数据。以下几种情况的分析都遵循该原则

2、长按HOME键,选择运行其他的程序时。

3、按下电源按键(关闭屏幕显示)时。

4、从activity A中启动一个新的activity时。

5、屏幕方向切换时,例如从竖屏切换到横屏时。
在屏幕切换之前,系统会销毁activity A,在屏幕切换之后系统又会自动地创建activity A,所以onSaveInstanceState一定会被执行

总而言之,onSaveInstanceState的调用遵循一个重要原则,即当系统“未经你许可”时销毁了你的activity,则onSaveInstanceState会被系统调用,这是系统的责任,因为它必须要提供一个机会让你保存你的数据(当然你不保存那就随便你了)。

不是异常状态下保存信息应该在哪个方法中呢?
onPause(这个方法不能太耗时)
在介绍onPause方法之前,还是想聊聊Activity的生命周期方法,相信大家对它应该有了初步的了解,不过在相应的生命周期方法中,我们应该做什么操作呢?推荐给大家一篇文章,我觉得不错。

关于onPause

onPause(), onStop(), onDestroy() are “killable after” lifecycle methods. This indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity’s code. Because onPause() is the first of the three, once the activity is created, onPause() is the last method that’s guaranteed to be called before the process can be killed—if the system must recover memory in an emergency, then onStop() and onDestroy() might not be called. Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage. However, you should be selective about what information must be retained during onPause(), because any blocking procedures in this method block the transition to the next activity and slow the user experience.
翻译过来就是:无论出现怎样的情况,比如程序突然死亡了,能保证的就是onPause方法是一定会调用的,而onStop和onDestory方法并不一定,所以这个特性使得onPause是持久化相关数据的最后的可靠时机。当然onPause方法不能做大量的操作,这会影响下一个Activity入栈。

刚才我们的测试结果还说明了一个道理,onSaveInstanceState并不是百分百调用的(比如点击了back键),显然一些永久性的数据,我们并不能在此中保存。

关于本文的结论就显而易见了,我们来一句话总结一下:

临时数据使用onSaveInstanceState保存恢复,永久性数据使用onPause方法保存。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值