android savedInstanceState 方法简单讲解

您所在的位置:网站首页 savedinstances怎么用 android savedInstanceState 方法简单讲解

android savedInstanceState 方法简单讲解

2024-06-14 04:22| 来源: 网络整理| 查看: 265

当程序快被杀死之前 也就是 生命周期 onpuse onstop 的时候当前界面处于不可见状态 会执行public void onSaveInstanceState(Bundle savedInstanceState) 这个方法 进行当前数据保存 以防止程序 因为内存不足被杀死丢失数据 若当程序因为内存不足被被系统gc 时再次启动这个程序 则会走onRestoreInstanceState () onCreate() 这两个方法读取之前被保存的数据 这个应用场景一般是玩游戏或者读书 到某个进度的时候 来个电话 或者操作其他应用使这个程序切换到后台 内存不足gc 掉了 可以保存当前进度

package com.yj.app.testcust; import android.app.Activity; import android.os.Bundle; import android.util.Log; import com.yj.app.R; public class AndroidTest extends Activity { private static final String TAG = "测试"; @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) { String ok = savedInstanceState.getString("ok"); Log.e(TAG, "savedInstanceState+IntTest="+"ok="+ok); } setContentView(R.layout.frg_test); Log.e(TAG, "生命周期第一次创建"); } @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.putString("ok", "我要保存数据"); super.onSaveInstanceState(savedInstanceState); Log.e(TAG, "onSaveInstanceState"); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); String ok = savedInstanceState.getString("ok"); Log.e(TAG, "onRestoreInstanceState+IntTest="+"+ok="+ok); } }

可以模拟一下这个效果 运行完程序后走 oncreate 生命周期第一次创建 当按home 键 改程序处于不可见状态随时都有可能被系统gc 掉

在这里插入图片描述 此时程序正在处于后台 我们点击一下如下图的小x 号 模拟应用因内存不足被后台杀死命令 然后再次点击程序 发现走了如下两个方法 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3