onCreate中的savedInstanceState有何具体作用

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

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

示例代码如下:

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

相关推荐