为什么 Intent 不能传递大数据

Intent 传递不同大小数据时的问题:

  • 传 512k 以下的数据是可以正常传递的;
  • 传 512k~1024k 的数据会出错,闪退;
  • 传 1024k 以上的数据会报错:TransactionTooLargeException;
  • 考虑到 Intent 还包括要启动的 Activity 等信息,实际可以传的数据略小于 512k;

Intent 携带信息的大小受 Binder 限制。数据以 Parcel 对象的形式存放在 Binder 传递缓存中。Binder 传递缓存有个限定的大小,通常是 1Mb。但同一个进程中所有的传输共享缓存空间,多个地方在进行传输时,即使它们各自传说的数据不超过大小显示。TrasnsactionTooLargeException 异常也可能会被抛出。因此,在使用 Intent 传递数据时,1Mb 并不是安全上限。因为 Binder 中可能正在处理其他的传输工作。不同的机型和系统版本,这个上限值也可能会不同。

普通的由 Zygote 进程 fork 出的进程,所映射的 Binder 内存大小是不到 1M 的。准确的说是:

c++ 复制代码
// /frameworks/native/libs/binder/ProcessState.cpp
#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)

如果传输的数据超过了这个大小,系统就会报错,因为 Binder 本身就是为了进程间频繁而灵活的通信所设计的,而不是为了拷贝大数据而使用的。

这个 TransactionTooLargeException 中也提到了这个:

java 复制代码
/*
 * The Binder transaction failed because it was too large.
 * 
 * The Binder transaction buffer has a limited fixed size, currently 1MB, which
 * is shared by all transactions in progress for the process.  Consequently this
 * exception can be thrown when there are many transactions in progress even when
 * most of the individual transactions are of moderate size.
 *
 */

Intent 携带的数据会经过 Binder 内核传递到目标中去,因为 Binder 映射内存的限制,所以 Intent 也受限制。

参考

Android 使用 intent 传递数据时的大小限制

相关推荐
阿pin10 分钟前
Android随笔-SharedPreferences
android·sp
茶栀(*´I`*)2 小时前
Android 测试入门指南:ADB 基础配置与常用设备管理命令解析
android·adb
gxgldyh4 小时前
Android Framework源码解析(七):BootAnimation 启动流程解析——开机动画是如何显示出来的?
android
达达尼昂4 小时前
在 Claude Cowork 中用好 Claude Fable 5
android·人工智能·后端
sTone873755 小时前
写时复制COW的第一性理解
android·c++·flutter
sTone873755 小时前
Zygote的第一性理解
android
sTone873755 小时前
类RN框架通过Service暴露卡片渲染能力给AI Chat
android·react native
灯火不休5 小时前
Android Studio & Flutter 构建命令完全指南
android
杉氧5 小时前
Ktor 全栈之路 (5):JWT 认证全流程实战 —— 打造安全通信闭环
android·架构·kotlin
️学习的小王5 小时前
Python + MySQL 学生信息管理系统实战教程
android·python·mysql