为什么 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 传递数据时的大小限制

相关推荐
2501_9151063240 分钟前
Perfdog 成本变高之后,Windows 上还能怎么做 iOS APP 性能测试
android·ios·小程序·https·uni-app·iphone·webview
愤怒的代码1 小时前
从开发调试到生产上线:全维度 Android 内存监控与分析体系构建
android·java·kotlin
jzlhll1231 小时前
Android最简化发布模块到mavenCentral
android·mavencentral
2501_915106321 小时前
iOS 安装了证书,HTTPS 还是抓不到
android·网络协议·ios·小程序·https·uni-app·iphone
好奇龙猫2 小时前
【人工智能学习-AI-MIT公开课13.- 学习:遗传算法】
android·人工智能·学习
TO_ZRG2 小时前
Unity打包安卓、iOS知识点
android·unity·android studio
周杰伦fans2 小时前
AndroidStudioJava国内镜像地址gradle
android·java·android-studio
艾莉丝努力练剑2 小时前
【Linux进程控制(一)】进程创建是呼吸,进程终止是死亡,进程等待是重生:进程控制三部曲
android·java·linux·运维·服务器·人工智能·安全
2501_924064112 小时前
2026年移动应用渗透测试流程方案及iOS与Android框架对比
android·ios
用户69371750013842 小时前
谷歌官方推荐:Android 性能优化全攻略——从工具到实战,两周提升 App 评分
android·android studio·android jetpack