Activity开发中需要保存状态的情形

11.Activity开发中需要保存状态的情形
	1.当进入onPause()方法后,应该保存一些状态,比如停止视频播放,停止网络连接,
将当前的内容存入Content provider中,但不能在这里使用大量的数据库操作,因为Activity
之间的切换是在调用完onPause()方法后,在调用第二个ActivityonCreate()方法,如果这
里太长时间,会影响activity间的切换,并导致不能响应的错误。
	这应该在OnResume()方法中将之前保存的状态恢复
	2.Activity 会被destory掉然后再重新创建的情形:
		1.屏幕旋转方向,因为旋转后的布局将不一样,需要重新导入布局文件
		2.onStop()方法调用后,因内存垃圾回收给kill掉了
		应该在OnStop()方法中保存信息,这里可以使用数据库来保存,因为这个方法被调用,
是第二个activity已经被创建完毕了再回调的方法,所以不会影响响应时间。可以把值存入一个键
值对的Bundle对象。
		
 		这应该在OnStart()方法中恢复之前的状态,通过读取Bundle或数据库来恢复状态
 
         实现保存与恢复需要实现几个方法:
               系统在释放资源准备kill掉你的activity之前会调用方法,
 onSaveInstanceState()并并传递一个Bundle对象,可以把需要保存的信息保存到这个对象上
             如:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
    
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}


         当activity被启动时,会调用onCreate(),也传递一个Bundle对象,可以在此恢复上
一次保存的状体,也会调用方法onRestoreInstanceState() 并传入
相同的Bundle对象,所以可以在此恢复之前在onSavaInstanceState()方法
中保存的状体信息
       如:
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);
   
    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
注意:这里必须调用父类的方法
当如也可以在onCreate()方法中恢复状体,可以这样,当推荐用前者,这样分工跟明确
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first
   
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
}

因为这有可能是第一次创建activity,所以可能bundle是null,所以需要检测一下
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值