onCreate中的savedInstanceState有何具体作用

来源:互联网 发布:淘宝重复铺货开店 编辑:程序博客网 时间:2024/04/27 23:45

在activity的生命周期中,只要离开了可见阶段,或者说失去了焦点,activity就很可能被进程终止了!,被KILL掉了,,这时候,就需要有种机制,能保存当时的状态,这就是savedInstanceState的作用。

      当一个Activity在PAUSE时,被kill之前,它可以调用onSaveInstanceState()来保存当前activity的状态信息(在paused状态时,要被KILLED的时候)。用来保存状态信息的Bundle会同时传给两个method,即onRestoreInstanceState() and onCreate().

示例代码如下:

[java] view plaincopy
  1. package com.myandroid.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.util.Log;  
  6.   
  7. public class AndroidTest extends Activity {  
  8.     private static final String TAG = "MyNewLog";  
  9.     /** Called when the activity is first created. */  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         // If an instance of this activity had previously stopped, we can  
  14.         // get the original text it started with.  
  15.         if(null != savedInstanceState)  
  16.         {  
  17.             int IntTest = savedInstanceState.getInt("IntTest");   
  18.             String StrTest = savedInstanceState.getString("StrTest");   
  19.             Log.e(TAG, "onCreate get the savedInstanceState+IntTest="+IntTest+"+StrTest="+StrTest);    
  20.         }  
  21.   
  22.         setContentView(R.layout.main);  
  23.         Log.e(TAG, "onCreate");  
  24.     }  
  25.   
  26.     @Override   
  27.     public void onSaveInstanceState(Bundle savedInstanceState) {   
  28.       // Save away the original text, so we still have it if the activity  
  29.       // needs to be killed while paused.  
  30.       savedInstanceState.putInt("IntTest"0);   
  31.       savedInstanceState.putString("StrTest""savedInstanceState test");   
  32.       super.onSaveInstanceState(savedInstanceState);   
  33.       Log.e(TAG, "onSaveInstanceState");  
  34.     }   
  35.   
  36.     @Override   
  37.     public void onRestoreInstanceState(Bundle savedInstanceState) {   
  38.       super.onRestoreInstanceState(savedInstanceState);   
  39.   
  40.       int IntTest = savedInstanceState.getInt("IntTest");   
  41.   
  42.       String StrTest = savedInstanceState.getString("StrTest");   
  43.   
  44.       Log.e(TAG, "onRestoreInstanceState+IntTest="+IntTest+"+StrTest="+StrTest);  
  45.     }   
  46. }  

本文转载自http://blog.csdn.net/eustoma/article/details/6217019

 

0 0
原创粉丝点击