学生心理健康网站建设论文,wordpress访问地图,设计上海2019,购物网站开发背景需求两种销毁第一种是正常的销毁#xff0c;比如用户按下Back按钮或者是activity自己调用了finish()方法#xff1b;另一种是由于activity处于stopped状态#xff0c;并且它长期未被使用#xff0c;或者前台的activity需要更多的资源#xff0c;这些情况下系统就会关闭后台的进…两种销毁第一种是正常的销毁比如用户按下Back按钮或者是activity自己调用了finish()方法另一种是由于activity处于stopped状态并且它长期未被使用或者前台的activity需要更多的资源这些情况下系统就会关闭后台的进程以恢复一些内存。需要注意的是这其中有一种情况就是屏幕旋转的问题当用户旋转手机屏幕每一次都会导致activity的销毁和重新建立。在第二种情况下尽管实际的activity实例已经被销毁但是系统仍然记得它的存在当用户返回到它的时候系统会创建出一个新的实例来代替它这里需要利用旧实例被销毁时候存下来的数据。这些数据被称为“instance state”是一个存在Bundle对象中的键值对集合。缺省状态下系统会把每一个View对象保存起来(比如EditText对象中的文本ListView中的滚动条位置等)即如果activity实例被销毁和重建那么不需要你编码layout状态会恢复到前次状态。但是如果你的activity需要恢复更多的信息比如成员变量信息则需要自己动手写了。onSaveInstanceState()如果要存储额外的数据必须覆写回调函数onSaveInstanceState().系统会在用户离开activity的时候调用这个函数并且传递给它一个Bundle object如果系统稍后需要重建这个activity实例它会传递同一个Bundle object到onRestoreInstanceState() 和 onCreate() 方法中去。当系统停止activity时它会调用onSaveInstanceState()(过程1)如果activity被销毁了但是需要创建同样的实例系统会把过程1中的状态数据传给onCreate()和onRestoreInstanceState()(图中标出的2和3)。存储Activity状态当系统停止activity时系统会调用onSaveInstanceState()状态信息会以键值对的形式存储下来。默认的实现中存储了activity的view系列的状态比如文本和滚动条位置等。要存储额外的信息必须自己实现onSaveInstanceState()并且给Bundle object加上键值对。static final String STATE_SCORE playerScore;static final String STATE_LEVEL playerLevel;...Overridepublic voidonSaveInstanceState(Bundle savedInstanceState) {//Save the users current game statesavedInstanceState.putInt(STATE_SCORE, mCurrentScore);savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);//Always call the superclass so it can save the view hierarchy statesuper.onSaveInstanceState(savedInstanceState);}要记得调用基类的实现以实现默认的实现。恢复Activity状态当activity重建时需要根据Bundle中的状态信息数据恢复activity。onCreate() 和onRestoreInstanceState()回调函数都会接收到这个Bundle。因为每次创建新的activity实例的或重建一个实例的时候都会调用onCreate()方法所以必须先检查是否Bundle是null如果是null则表明是要创建一个全新的对象而不是重建一个上次被销毁的对象。比如onCreate()方法可以这么写Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); //Always call the superclass first//Check whether were recreating a previously destroyed instanceif (savedInstanceState ! null) {//Restore value of members from saved statemCurrentScore savedInstanceState.getInt(STATE_SCORE);mCurrentLevelsavedInstanceState.getInt(STATE_LEVEL);}else{//Probably initialize members with default values for a new instance}...}除了在onCreate()中恢复状态外也可以选择在onRestoreInstanceState()中实现这个函数在onStart()之后调用。只有在有数据要恢复的时候系统会调用onRestoreInstanceState()所以不必检查Bundle是否为null。public voidonRestoreInstanceState(Bundle savedInstanceState) {//Always call the superclass so it can restore the view hierarchysuper.onRestoreInstanceState(savedInstanceState);//Restore state members from saved instancemCurrentScore savedInstanceState.getInt(STATE_SCORE);mCurrentLevelsavedInstanceState.getInt(STATE_LEVEL);}此处也要注意不要忘记调用基类实现。我是天王盖地虎的分割线