蓝色天空网mbsky.com · 知识 · 实践 · 创造Android · 本地阅读预览
教程 / 移动开发 / Android

4.5.2 Intent之复杂数据的传递

掌握 Intent/Bundle 传递数组、集合、JSON、Serializable 与 Parcelable 对象的选型与实现,剖析 Bitmap 传输限制,以及自定义 Application 和单例在系统后台回收进程时的空指针陷阱与防御策略。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Intent 传递基础类型、数组与常见集合

跨页面传递单个基础数据时,可直接调用 `Intent.putExtra()` 与对应的 `getXxxExtra()`;需要组合多个字段时,先装入键值容器 `Bundle` 再经 `intent.putExtras(bundle)` 统一传递。对于数组类型(如 `String[]`、`int[]`、`float[]`),`Bundle` 均提供原生 `putStringArray()` / `getStringArray()` 等类型化接口。

传递集合按元素类型分为三种情形:对于 `ArrayList<String>` 或 `ArrayList<Integer>`,直接使用 `putStringArrayListExtra()` / `putIntegerArrayListExtra()` 及对应 getter;对于自定义对象列表 `List<Object>`,可令元素实现 `Serializable` 接口并将列表强转为 `Serializable` 写入(更推荐让元素实现 `Parcelable` 并使用 `putParcelableArrayListExtra()`);对于 `List<Map<String, Object>>` 等嵌套结构,原示例通过外层再套一层 `ArrayList` 强塞进 `putParcelableArrayList()` 存在泛型擦除隐患,生产代码更建议统一采用 `Serializable` 包装类、JSON 序列化或共享数据源传递。

传递自定义对象(JSON / Serializable / Parcelable)与 Bitmap

向另一页面传递业务对象通常有三条路线:一是借助 Gson/Moshi/kotlinx.serialization 将对象转为 JSON 字符串传入并在目标页反序列化,结构直观且易跨端复用;二是令模型实现 Java 标准接口 `Serializable`,编码最省事,但底层反射会产生较多临时对象、易引发 GC 抖动,适合磁盘持久化或网络归档;三是实现 Android 专用的 `Parcelable` 接口,重写 `writeToParcel()`、`describeContents()` 并定义静态常量 `CREATOR`(务必确保写入与读取字段顺序严格一致,现代 Kotlin 开发可直接加 `@Parcelize` 注解自动生成),其在内存跨进程封送时性能显著优于 `Serializable`,但不适合用于磁盘长期持久化。虽然 `Bitmap` 默认实现了 `Parcelable` 可直接放入 `Bundle`,但未压缩位图极易超过 Binder 1MB 缓冲区触发 `TransactionTooLargeException`,实际工程应传递图片路径、URI 或内存缓存键而非直接传递大图 `Bitmap`。

Application 全局对象、单例传参与后台进程回收空指针陷阱

面对 `Activity1 -> Activity2 -> Activity3 -> Activity4` 这类跨多级页面的共享数据需求,传统做法常借助自定义 `Application` 子类(在清单 `<application android:name=".MyApp">` 注册,并在 `onCreate()` 中先调用 `super.onCreate()` 再保存静态引用 `instance = this`——注意原示例漏写了 `super.` 写成 `onCreate();` 会导致无限递归栈溢出)或线程安全的单例类 `XclSingleton` 在内存中共享状态。然而必须高度警惕 Android 的进程回收机制:当应用切入后台因内存不足被系统杀死后,用户再次点开时系统会新建一个空白的 `Application` 实例并直接恢复上次停留的 `Activity2`,此时内存中的 `Application` 字段、单例与静态变量全部重置为初始空值,若 `Activity2` 不做判空检查就会直接 `NullPointerException` 崩溃。因此,关键业务状态必须结合本地持久化(`SharedPreferences`/DataStore/SQLite)或 `SavedStateHandle` 保存,并在读取全局内存缓存时做好判空与重建兜底。

运行 Intent 集合/JSON/Serializable/Parcelable 序列化对比与后台进程回收陷阱验证

python · 阅读源码
"""Offline Android Intent complex data passing: arrays, collections, JSON/Serializable/Parcelable, and Application process death verifier."""
import json
import pickle
import struct

VERSION = "CPython 3.12.14 offline Android component/IPC/Fragment verifier (Android SDK/emulator absent)"


def case_intent_bundle_primitives_arrays_lists():
    bundle = {}
    bundle["StringArray"] = ["条目A", "条目B"]
    bundle["IntList"] = [10, 20, 30]
    bundle["StringList"] = ["Java", "Kotlin"]
    bundle["SerializableList"] = [{"id": 1, "name": "Item1"}, {"id": 2, "name": "Item2"}]
    nested_maps = [[{"key1": "value1", "key2": "value2"}]]
    bundle["NestedMapList"] = nested_maps

    actual = {
        "string_array": bundle["StringArray"],
        "int_list_sum": sum(bundle["IntList"]),
        "string_list_len": len(bundle["StringList"]),
        "serializable_first_name": bundle["SerializableList"][0]["name"],
        "nested_map_key1": bundle["NestedMapList"][0][0]["key1"],
    }
    expected = {
        "string_array": ["条目A", "条目B"],
        "int_list_sum": 60,
        "string_list_len": 2,
        "serializable_first_name": "Item1",
        "nested_map_key1": "value1",
    }
    return {
        "name": "intent_bundle_primitives_arrays_lists",
        "summary": "验证 Bundle/Intent 对字符串数组、整型/字符串 ArrayList、Serializable 对象列表及嵌套 Map 列表的读写往返。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_json_serializable_parcelable_comparison():
    # 1. JSON roundtrip (Gson-style Book + Author)
    book_obj = {"id": 1, "title": "Java编程思想", "author": {"id": 1, "name": "Bruce Eckel"}}
    book_json = json.dumps(book_obj, ensure_ascii=False)
    book_decoded = json.loads(book_json)

    # 2. Parcelable ordered stream (write order MUST match read order)
    def write_parcel(book_name: str, author: str, publish_time: int) -> bytes:
        b1, b2 = book_name.encode("utf-8"), author.encode("utf-8")
        return struct.pack(">i", len(b1)) + b1 + struct.pack(">i", len(b2)) + b2 + struct.pack(">i", publish_time)

    def read_parcel(raw: bytes) -> dict:
        pos = 0
        l1, = struct.unpack(">i", raw[pos:pos + 4]); pos += 4
        s1 = raw[pos:pos + l1].decode("utf-8"); pos += l1
        l2, = struct.unpack(">i", raw[pos:pos + 4]); pos += 4
        s2 = raw[pos:pos + l2].decode("utf-8"); pos += l2
        year, = struct.unpack(">i", raw[pos:pos + 4])
        return {"bookName": s1, "author": s2, "publishTime": year}

    parcel_bytes = write_parcel("Android开发指南", "TechAuthor", 2024)
    parcel_decoded = read_parcel(parcel_bytes)

    # 3. Serializable vs Parcelable overhead check (pickle as Java Serializable analogue vs compact Parcel)
    serializable_bytes = pickle.dumps(parcel_decoded, protocol=4)

    # 4. Bitmap Binder IPC size guard (1024x1024 ARGB_8888 = 4 MB >> 1 MB Binder limit)
    bitmap_bytes = 1024 * 1024 * 4
    bitmap_exceeds_binder_1mb = bitmap_bytes > 1024 * 1024

    actual = {
        "json_author_name": book_decoded["author"]["name"],
        "parcel_decoded": parcel_decoded,
        "parcel_smaller_than_serializable": len(parcel_bytes) < len(serializable_bytes),
        "bitmap_4mb_exceeds_binder_limit": bitmap_exceeds_binder_1mb,
    }
    expected = {
        "json_author_name": "Bruce Eckel",
        "parcel_decoded": {"bookName": "Android开发指南", "author": "TechAuthor", "publishTime": 2024},
        "parcel_smaller_than_serializable": True,
        "bitmap_4mb_exceeds_binder_limit": True,
    }
    return {
        "name": "json_serializable_parcelable_comparison",
        "summary": "验证 JSON、Serializable 与顺序 Parcelable 序列化往返对比,并校验直接经 Intent 传递大图 Bitmap 触发 Binder 1MB 上限风险。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_application_and_singleton_process_death_trap():
    # Simulates Activity1 storing state in Application & Singleton -> OS kills background process -> Activity2 recreated
    class ProcessRuntime:
        def __init__(self):
            self.app_state: str | None = None
            self.singleton_map: dict = {}

    # Initial process
    proc1 = ProcessRuntime()
    proc1.app_state = "user_account_42"
    proc1.singleton_map["token"] = "tok_abc"
    disk_backup = {"user_account": proc1.app_state}

    # OS kills process in background; user returns directly to Activity2 -> fresh Application + empty Singleton!
    proc2 = ProcessRuntime()
    naive_read = proc2.app_state  # None -> NullPointerException if dereferenced without check!
    safe_read = proc2.app_state or disk_backup.get("user_account")

    actual = {
        "proc1_state": proc1.app_state,
        "proc1_singleton_token": proc1.singleton_map["token"],
        "proc2_after_os_kill_naive": naive_read,
        "proc2_singleton_empty_after_kill": len(proc2.singleton_map) == 0,
        "proc2_safe_fallback": safe_read,
        "source_oncreate_bug": "Missing super.onCreate() causes StackOverflowError recursion",
    }
    expected = {
        "proc1_state": "user_account_42",
        "proc1_singleton_token": "tok_abc",
        "proc2_after_os_kill_naive": None,
        "proc2_singleton_empty_after_kill": True,
        "proc2_safe_fallback": "user_account_42",
        "source_oncreate_bug": "Missing super.onCreate() causes StackOverflowError recursion",
    }
    return {
        "name": "application_and_singleton_process_death_trap",
        "summary": "模拟后台进程被系统回收后直接恢复 Activity2 导致 Application 与单例数据归空(空指针陷阱),验证持久化回退策略并指出原 onCreate 递归笔误。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_intent_bundle_primitives_arrays_lists(),
        case_json_serializable_parcelable_comparison(),
        case_application_and_singleton_process_death_trap(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证数组/集合读写、JSON 与有序 Parcelable 往返及 4MB Bitmap 超出 Binder 上限校验,并模拟系统回收进程后恢复 Activity2 导致全局内存归空的防御处理。
运行 Intent 集合/JSON/Serializable/Parcelable 序列化对比与后台进程回收陷阱验证

所需环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。

当前源码 SHA256:3f07c191b00c8eda4b05b68d668c78813651bf54790d25d3a2d224e211134114

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载4.5.2 Intent之复杂数据的传递实验

所需环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。

ZIP SHA256:28d08a6414967a6be95b58f66abcb8e59bc7b4604bbbc20d847aa5038d8b8daa

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么不能把用户登录态或关键页面参数仅仅保存在自定义 Application 或全局静态单例中?系统回收进程后再恢复页面会发生什么?

展开参考解答

应用在后台被系统回收后,用户重新切回时系统会创建全新的 Application 实例并直接恢复栈顶 Activity,此时所有静态字段、单例和 Application 成员变量均会恢复默认值(如 null),直接读取将触发 NullPointerException;关键数据需通过 Intent/savedInstanceState 或持久化存储兜底恢复。

规范与官方依据