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

来源:互联网 发布:php throw exception 编辑:程序博客网 时间:2024/06/11 15:59
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";@Overridepublic 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()方法中恢复状体,可以这样,当推荐用前者,这样分工跟明确
@Overrideprotected 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,所以需要检测一下
原创粉丝点击