• onCreate中的savedInstanceState有何具体作用


    最近在查看OnCreate(saveInstanceState)时候,只懂得其中是为了保存当activity失去焦点的时候的状态,却不知其实如何实现的,今天发现一个好文章,和大家分享一下哦。
    在activity的生命周期中,只要离开了可见阶段,或者说失去了焦点,activity就很可能被进程终止了!,被KILL掉了,,这时候,就需要有种机制,能保存当时的状态,这就是savedInstanceState的作用。       当一个Activity在PAUSE时,被kill之前,它可以调用onSaveInstanceState()来保存当前activity的状态信息。用来保存状态信息的Bundle会同时传给两个method,即onRestoreInstanceState() and onCreate(). 示例代码如下:

    • package com.myandroid.test;
    • import android.app.Activity;
    • import android.os.Bundle;
    • import android.util.Log;
    • public class AndroidTest extends Activity {
    •     private   static  final String TAG = "MyNewLog";
    •     /** Called when the activity is first created. */
    •     @Override
    •     public  void onCreate(Bundle savedInstanceState) {
    •         super.onCreate(savedInstanceState);
    •         // If an instance of this activity had previously stopped, we can
    •         // get the original text it started with.
    •         if(null != savedInstanceState)
    •         {
    •             int IntTest = savedInstanceState.getInt("IntTest");
    •             String StrTest = savedInstanceState.getString("StrTest");
    •             Log.e(TAG, "onCreate get the savedInstanceState+IntTest="+IntTest+"+StrTest="+StrTest);
    •         }
    •         setContentView(R.layout.main);
    •         Log.e(TAG, "onCreate");
    •     }
    •     @Override
    •     public  void onSaveInstanceState(Bundle savedInstanceState) {
    •       // Save away the original text, so we still have it if the activity
    •       // needs to be killed while paused.
    •       savedInstanceState.putInt("IntTest", 0);
    •       savedInstanceState.putString("StrTest", "savedInstanceState test");
    •       super.onSaveInstanceState(savedInstanceState);
    •       Log.e(TAG, "onSaveInstanceState");
    •     }
    •     @Override
    •     public   void onRestoreInstanceState(Bundle savedInstanceState) {
    •       super.onRestoreInstanceState(savedInstanceState);
    •       int IntTest = savedInstanceState.getInt("IntTest");
    •       String StrTest = savedInstanceState.getString("StrTest");
    •       Log.e(TAG, "onRestoreInstanceState+IntTest="+IntTest+"+StrTest="+StrTest);
    •     }
    • }
  • 相关阅读:
    发布一个用于WinCE的矢量图控件
    [非原创]树和图的遍历
    对ZOJ第1146题的解答:LCDisplay
    [c#]可在任意位置弹出的BalloonTip
    windows程序开发中c++和c#的对照
    关于编译时的warning treated as error
    flyweight模式和图元几何变换
    i++和++i作为参数时的编译器处理方式分析~
    用小数数组计算E值(对ZOJ第1113题的解答)
    显示SendMessage和PostMessage的区别
  • 原文地址:https://www.cnblogs.com/yunqingabc/p/4301784.html
Copyright © 2020-2023  润新知