onCreate中的savedInstanceState的作用

本文解析了Android中Activity生命周期内的onCreate方法中savedInstanceState参数的作用。通过实例演示了如何在onSaveInstanceState方法中保存状态,并在onCreate及onRestoreInstanceState方法中恢复状态,确保了在Activity被销毁重建时仍能保持原有状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

onCreate中的savedInstanceState的作用2010-11-28 17:23 (转载自http://blog.youkuaiyun.com/xiaoxiao_job/archive/2010/08/31/5852811.aspx,感谢作者的智慧) 在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);
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值