onCreate中的savedInstanceState有何具体作用?具体例子?

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

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

示例代码如下:

 1 package com.myandroid.test;
 2 
 3 import android.app.Activity;
 4 
 5 import android.os.Bundle;
 6 
 7 import android.util.Log;
 8 
 9 public class AndroidTest extends Activity {
10 
11      private static final String TAG = "MyNewLog";
12 
13     /** Called when the activity is first created. */
14 
15     @Override
16 
17     public void onCreate(Bundle savedInstanceState) {
18 
19         super.onCreate(savedInstanceState);
20 
21         // If an instance of this activity had previously stopped, we can
22 
23         // get the original text it started with.
24 
25         if(null != savedInstanceState)
26 
27         {
28 
29             int IntTest = savedInstanceState.getInt("IntTest");
30 
31             String StrTest = savedInstanceState.getString("StrTest");
32 
33             Log.e(TAG, "onCreate get the savedInstanceState+IntTest="+IntTest+"+StrTest="+StrTest);        
34 
35         }
36 
37         setContentView(R.layout.main);
38 
39         Log.e(TAG, "onCreate");
40 
41     }
42 
43    
44 
45     @Override
46 
47     public void onSaveInstanceState(Bundle savedInstanceState) {
48 
49         // Save away the original text, so we still have it if the activity
50 
51         // needs to be killed while paused.
52 
53       savedInstanceState.putInt("IntTest", 0);
54 
55       savedInstanceState.putString("StrTest", "savedInstanceState test");
56 
57       super.onSaveInstanceState(savedInstanceState);
58 
59       Log.e(TAG, "onSaveInstanceState");
60 
61     }
62 
63    
64 
65     @Override
66 
67     public void onRestoreInstanceState(Bundle savedInstanceState) {
68 
69       super.onRestoreInstanceState(savedInstanceState);
70 
71       int IntTest = savedInstanceState.getInt("IntTest");
72 
73       String StrTest = savedInstanceState.getString("StrTest");
74 
75       Log.e(TAG, "onRestoreInstanceState+IntTest="+IntTest+"+StrTest="+StrTest);
76 
77     }
78 
79 }

 

转载于:https://www.cnblogs.com/liu666bin/archive/2013/01/05/2845963.html

你可能感兴趣的:(onCreate中的savedInstanceState有何具体作用?具体例子?)