• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
在北京的四川小伙
一切不以结婚为目的的恋爱,都是耍流氓 -----爱因斯坦●涛
博客园    首页    新随笔    联系   管理    订阅  订阅

onCreate中的savedInstanceState作用

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

      当一个Activity在PAUSE时,被kill之前,它可以调用onSaveInstanceState()来保存当前activity的状态信息(在paused状态时,要被KILLED的时候)。用来保存状态信息的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);
    } 
}

 

如今的编程是一场程序员和上帝的竞赛,程序员要开发出更大更好、傻瓜都会用到软件。而上帝在努力创造出更大更傻的傻瓜。目前为止,上帝是赢的。 QQ:6203142 -----在北京的四川小伙
posted @ 2015-03-27 11:26  在北京的四川小伙  阅读(161)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3