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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM