| 
 | 
 
1. Bundle 基本概念 
Bundle 是 Android 中用于存储和传递数据的容器类,它以键值对的形式存储数据,类似于 HashMap,但专门用于 Android 组件之间的数据传递- // Bundle 的基本使用示例
 
 - Bundle bundle = new Bundle();
 
 - bundle.putString("key", "value");
 
 - bundle.putInt("number", 123);
 
 
  复制代码 2. 在 onCreate 方法中的作用 
在 MainActivity 的 onCreate 方法中,Bundle savedInstanceState 参数用于恢复 Activity 的状态: 
当 Activity 首次创建时,该参数为 null 
当 Activity 被系统销毁后重新创建时,该参数包含之前保存的状态信息 
 
- public void onCreate(Bundle savedInstanceState) {
 
 -     super.onCreate(savedInstanceState);
 
 -     // savedInstanceState 包含了 Activity 销毁前保存的状态
 
 -     // 可以从中恢复数据
 
 - }
 
 
  复制代码 3. 状态保存与恢复机制 
Android 系统使用 Bundle 实现 Activity 的状态保存与恢复: 
 
- // 保存状态
 
 - @Override
 
 - protected void onSaveInstanceState(Bundle outState) {
 
 -     super.onSaveInstanceState(outState);
 
 -     outState.putString("data_key", "data_value");
 
 - }
 
  
- // 恢复状态
 
 - @Override
 
 - protected void onCreate(Bundle savedInstanceState) {
 
 -     super.onCreate(savedInstanceState);
 
 -     if (savedInstanceState != null) {
 
 -         String data = savedInstanceState.getString("data_key");
 
 -     }
 
 - }
 
 
  复制代码 4. Bundle 支持的数据类型 
Bundle 支持多种数据类型,包括基本数据类型、数组、实现了 Parcelable 或 Serializable 接口的对象等: 
基本类型:int, float, boolean, String 等 
数组类型:int[], String[] 等 
对象类型:必须实现 Parcelable 或 Serializable 
5. 在 Intent 传递中的应用 
Bundle 也常用于在 Activity 之间传递数据: 
 
- Intent intent = new Intent(this, AnotherActivity.class);
 
 - Bundle bundle = new Bundle();
 
 - bundle.putString("message", "Hello");
 
 - intent.putExtras(bundle);
 
 - startActivity(intent);
 
 
  复制代码 在目标 Activity 中获取数据: 
- Bundle bundle = getIntent().getExtras();
 
 - if (bundle != null) {
 
 -     String message = bundle.getString("message");
 
 - }
 
 
  复制代码 总结来说,Bundle 是 Android 中用于存储和传递轻量级数据的重要工具,特别是在 Activity 生命周期管理、组件间通信等场景中发挥着关键作用。 
 
 
 |   
 
 
 
 |