Android intent 传递数据的大小限制

2024-05-28 11:38

本文主要是介绍Android intent 传递数据的大小限制,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

gityuan – startActivity启动过程分析 – 大佬写的真的好,置顶了


Intent 究竟能传递多大的数据?

    • 1. Intent 传递不同大小数据时的问题
    • 2. 问题分析
      • 2.1 intent 传递数据测试
      • 2.2 从 crash log 角度分析
      • 2.3 startActivity 流程探究
    • 3. Binder 传输数据的 大小限制
    • 4. intent 传递数据大小限制问题的小结
      • 4.1 一句话概括这个问题
      • 4.2 分析
    • 4. 为什么 `Binder` 要限制传输数据的大小
    • 5. 从 Intent 传递数据的原理分析
    • 6. 解决方法
    • 7. 参考链接

我们知道可以通过 Intentbundleactivityfragment 间进行通信,但是 Intent 传递数据时,如果数据太大,可能会出现异常。

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

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

2. 问题分析

2.1 intent 传递数据测试

val intent = Intent(this, MainActivity2::class.java).apply {val data2 = ByteArray(1024 * 1024)putExtra("111", data2)
}
startActivity(intent)

error:

Caused by: android.os.TransactionTooLargeException: data parcel size 1049012 bytesat android.os.BinderProxy.transactNative(Native Method)at android.os.BinderProxy.transact(BinderProxy.java:511)at android.app.IActivityTaskManager$Stub$Proxy.startActivity(IActivityTaskManager.java:3969)at android.app.Instrumentation.execStartActivity(Instrumentation.java:1716)at android.app.Activity.startActivityForResult(Activity.java:5260) at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675) at android.app.Activity.startActivityForResult(Activity.java:5218) at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662) at android.app.Activity.startActivity(Activity.java:5589) at android.app.Activity.startActivity(Activity.java:5557) 

2.2 从 crash log 角度分析

Intent 中传入一个 Parcelable 对象, 例如传入一个 bitmap 对象。Bitmap 实现了 Parcelable 接口,并且可以通过 getByteCount() 得知所占内存大小。测试时候报出如下信息

 V/ActivityManager: Broadcast: Intent { act=intent_bi flg=0x10 (has extras) } ordered=false userid=0 callerApp=ProcessRecord{27aeaaf5 31217:com.rustfisher.basic4/u0a113}E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!W/BroadcastQueue: Failure sending broadcast Intent { act=intent_bi flg=0x10 (has extras) }android.os.TransactionTooLargeExceptionat android.os.BinderProxy.transactNative(Native Method)at android.os.BinderProxy.transact(Binder.java:504)at android.app.ApplicationThreadProxy.scheduleRegisteredReceiver(ApplicationThreadNative.java:1170)at com.android.server.am.BroadcastQueue.performReceiveLocked(BroadcastQueue.java:576)at com.android.server.am.BroadcastQueue.deliverToRegisteredReceiverLocked(BroadcastQueue.java:848)at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:917)at com.android.server.am.BroadcastQueue$BroadcastHandler.handleMessage(BroadcastQueue.java:254)at android.os.Handler.dispatchMessage(Handler.java:111)at android.os.Looper.loop(Looper.java:194)at android.os.HandlerThread.run(HandlerThread.java:61)at com.android.server.ServiceThread.run(ServiceThread.java:46)

查看异常类 TransactionTooLargeException,它继承了 RemoteExceptio:

package android.os;
public class TransactionTooLargeException extends RemoteException {public TransactionTooLargeException() {super();}public TransactionTooLargeException(String msg) {super(msg);}
}

追踪到 Binder,它的 transactNative 方法会报出 RemoteException:

public native boolean transactNative(int code, Parcel data, Parcel reply,int flags) throws RemoteException;

由此可以看出,抛出异常与 Binder 有关。

2.3 startActivity 流程探究

首先, ContextActivity 都含有 startActivity, 但两者最终都调用了 Activity 中的 startActivity:

    @Overridepublic void startActivity(Intent intent, @Nullable Bundle options) {if (options != null) {startActivityForResult(intent, -1, options);} else {// Note we want to go through this call for compatibility with// applications that may have overridden the method.startActivityForResult(intent, -1);}}

startActivity 最终会调用自身的 startActivityForResult,省略了嵌套 activity 的代码:

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,@Nullable Bundle options) {if (mParent == null) {options = transferSpringboardActivityOptions(options);Instrumentation.ActivityResult ar =mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);if (ar != null) {mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(),ar.getResultData());}if (requestCode >= 0) {// If this start is requesting a result, we can avoid making// the activity visible until the result is received.  Setting// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the// activity hidden during this time, to avoid flickering.// This can only be done when a result is requested because// that guarantees we will get information back when the// activity is finished, no matter what happens to it.mStartedActivity = true;}cancelInputsAndStartExitTransition(options);// TODO Consider clearing/flushing other event sources and events for child windows.} else {if (options != null) {mParent.startActivityFromChild(this, intent, requestCode, options);} else {// Note we want to go through this method for compatibility with// existing applications that may have overridden it.mParent.startActivityFromChild(this, intent, requestCode);}}}

然后系统会调用 Instrumentation 中的 execStartActivity 方法:

public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,Intent intent, int requestCode, Bundle options) {IApplicationThread whoThread = (IApplicationThread) contextThread;......try {intent.migrateExtraStreamToClipData(who);intent.prepareToLeaveProcess(who);int result = ActivityTaskManager.getService().startActivity(whoThread,who.getBasePackageName(), who.getAttributionTag(), intent,intent.resolveTypeIfNeeded(who.getContentResolver()), token,target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);checkStartActivityResult(result, intent);} catch (RemoteException e) {throw new RuntimeException("Failure from system", e);}return null;}

接着调用了 ActivityManger.getService().startActivity, getService 返回的是系统进程中的 AMSapp 进程中的 binder 代理:

/** @hide */
public static IActivityTaskManager getService() {return IActivityTaskManagerSingleton.get();
}private static final Singleton<IActivityManager> IActivityManagerSingleton = new Singleton<IActivityManager>() {@Overrideprotected IActivityManager create() {final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);final IActivityManager am = IActivityManager.Stub.asInterface(b);return am;}
};

接下来就是 App 进程调用 AMS 进程中的方法了。简单来说,系统进程中的 AMS 集中负责管理所有进程中的 Activity

App 进程与系统进程需要进行双向通信。比如打开一个新的 Activity,则需要调用系统进程 AMS中的方法进行实现,AMS 等实现完毕需要回调app进程中的相关方法进行具体 activity生命周期的回调。

所以我们在 intent 中携带的数据也要从 APP 进程传输到 AMS 进程,再由 AMS 进程传输到目标Activity 所在进程。

有同学可能由疑问了,目标 Acitivity 所在进程不就是 APP 进程吗?其实不是的,我们可以在 Manifest.xml 中设置 android:process 属性来为 Activity, Service 等指定单独的进程,所以 ActivitystartActivity 方法是原生支持跨进程通信的

3. Binder 传输数据的 大小限制

在这里插入图片描述
普通的由 Zygote 孵化而来的用户进程,所映射的Binder内存大小是不到1M的,准确说是

#define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))

这个限制定义在 frameworks/native/+/4d2f4bb/libs/binder/ProcessState.cpp类中,如果传输数据超过这个大小,系统就会报错,因为Binder本身就是为了进程间频繁而灵活的通信所设计的,并不是为了拷贝大数据而使用的.

其实在 TransactionTooLargeException 中也提到了这个

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.

4. intent 传递数据大小限制问题的小结

4.1 一句话概括这个问题

startActivity携带的数据会经过 Binder内核再传递到目标Activity中去,因为binder映射内存的限制,所以startActivity也就会这个限制了

4.2 分析

Intent 携带信息的大小其实是受 Binder 限制。本文标题也可以改为 Binder传递数据大小限制。

数据以 Parcel 对象的形式存放在 Binder传递缓存中。如果数据或返回值比传递 buffer 大,则此次传递调用失败并抛出 TransactionTooLargeException 异常。

Binder 传递缓存有一个限定大小,通常是 1Mb。但同一个进程中所有的传输共享缓存空间。
多个地方在进行传输时,即时它们各自传输的数据不超出大小限制,TransactionTooLargeException异常也可能会被抛出。

在使用 Intent 传递数据时,1Mb 并不是安全上限。因为 Binder 中可能正在处理其它的传输工作。
不同的机型和系统版本,这个上限值也可能会不同。

在其它地方,例如 onSaveInstanceState(@NonNull Bundle outState),也可能会遇到与 Binder 有关的类似问题。

4. 为什么 Binder 要限制传输数据的大小

个人推测,作为一种 IPC 的方式,Binder 并不是为传输大量数据而设计。传输大量数据,可以考虑URL 之类的方法( 只传递索引,不传递具体的数据。或者其他类似的做法)。

5. 从 Intent 传递数据的原理分析

通过 intentbundle 的源码可以看到它们都是实现了 Parcelable ,其实就是通过序列化来实现通信的。提到 Parcelable 就不得不提 Serializable,这里引用一段网上的总结:

介绍Parcelable不得不先提一下Serializable接口,Serializable是Java为我们提供的一个标准化的序列化接口,那什么是序列化呢? —- 简单来说就是将对象转换为可以传输的二进制流(二进制序列)的过程,这样我们就可以通过序列化,转化为可以在网络传输或者保存到本地的流(序列),从而进行传输数据 ,那反序列化就是从二进制流(序列)转化为对象的过程.

Parcelable 是Android为我们提供的序列化的接口, Parcelable 相对于 Serializable 的使用相对复杂一些,但 Parcelable 的效率相对 Serializable 也高很多,这一直是 Google工程师引以为傲的,有时间的可以看一下 ParcelableSerializable 的效率对比 Parcelable vs Serializable 号称快10倍的效率

Yet another post on Serializable vs Parcelable

Parcelable 的底层使用了 Parcel 机制。传递实际上是使用了 binder 机制,binder 机制会将 Parcel序列化的数据写入到一个共享内存中,读取时也是 binder 从共享内存中读出字节流,然后 Parcel 反序列化后使用。这就是 IntentBundle 能够在 activity或者跨进程通信的原理。

  • 参考“探索startActivity流程及在Activity间是如何传递Intent的

关于 ParcelableSerializable 的区别,同样引用一段网上的总结:

ParcelableSerializable 都是实现序列化并且都可以用于 Intent 间传递数据, SerializableJava 的实现方式,可能会频繁的 IO 操作,所以消耗比较大,但是实现方式简单 ParcelableAndroid 提供的方式, 效率比较高,但是实现起来复杂一些 , 二者的选取规则是:

  • 内存序列化上选择Parcelable
  • 存储到设备或者网络传输上选择Serializable(当然Parcelable也可以但是稍显复杂)

当我们用Intent传输过大数据时,一般logcat会报出 TransactionTooLargeException 错误,谷歌官方对这个错误的描述如下:

The Binder transaction failed because it was too large.
During a remote procedure call, the arguments and the return value of the call are transferred as
Parcel objects stored in the Binder transaction buffer. If the arguments or the return value are too
large to fit in the transaction buffer, then the call will fail and TransactionTooLargeException
will be thrown.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.There are two possible outcomes when a remote procedure call throws TransactionTooLargeException.
Either the client was unable to send its request to the service (most likely if the arguments were
too large to fit in the transaction buffer), or the service was unable to send its response back to
the client (most likely if the return value was too large to fit in the transaction buffer). It is
not possible to tell which of these outcomes actually occurred. The client should assume that a
partial failure occurred.The key to avoiding TransactionTooLargeException is to keep all transactions relatively small.
Try to minimize the amount of memory needed to create a Parcel for the arguments and the return
value of the remote procedure call. Avoid transferring huge arrays of strings or large bitmaps.
If possible, try to break up big requests into smaller pieces.If you are implementing a service, it may help to impose size or complexity contraints on the
queries that clients can perform. For example, if the result set could become large, then don't
allow the client to request more than a few records at a time. Alternately, instead of returning
all of the available data all at once, return the essential information first and make the client
ask for additional information later as needed.

简单来说,我们上面提到了 Parcel 机制使用了一个共享内存,这个共享内存就叫 Binder transaction buffer,这块内存有一个大小限制,目前是 1MB,而且共用的,当超过了这个大小就会报错。

也就是说不仅仅是一次性传递大数据会出问题,当同时传递很多数据,尽管每个都不超过1MB,但是总大小超过 1MB也会出错

6. 解决方法

Activity之间传递数据的方式及常见问题总结

  • 限制传递数据量
  • 改变数据传输方式(参见Activity之间传递数据的方式)
  • 静态static
  • 单例
  • Application
  • 持久化
  • 使用容器的单例模式

7. 参考链接

  • Activity间通过Intent传递数据的大小限制 – 具体数据博客
  • 学Android 这么久,intent传递数据最大多少呢?

  • TransactionTooLargeException 官网详细解读
  • Activity之间使用intent传递大量数据带来问题总结
  • Android中Intent/Bundle的通信原理及大小限制(Parcelable原理及与Serializable的区别
  • Activity间通过Intent传递数据的大小限制 – 具体数据
  • Android remote method data limit
  • https://developer.android.com/reference/android/os/TransactionTooLargeException
  • Android中Intent/Bundle的通信原理及大小限制(Parcelable原理及与Serializable的区别)
  • https://stackoverflow.com/questions/12819617/issue-passing-large-data-to-second-activity

这篇关于Android intent 传递数据的大小限制的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1010467

相关文章

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

Pyserial设置缓冲区大小失败的问题解决

《Pyserial设置缓冲区大小失败的问题解决》本文主要介绍了Pyserial设置缓冲区大小失败的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录问题描述原因分析解决方案问题描述使用set_buffer_size()设置缓冲区大小后,buf

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

详解C++中类的大小决定因数

《详解C++中类的大小决定因数》类的大小受多个因素影响,主要包括成员变量、对齐方式、继承关系、虚函数表等,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 非静态数据成员示例:2. 数据对齐(Padding)示例:3. 虚函数(vtable 指针)示例:4. 继承普通继承虚继承5.

Android中Dialog的使用详解

《Android中Dialog的使用详解》Dialog(对话框)是Android中常用的UI组件,用于临时显示重要信息或获取用户输入,本文给大家介绍Android中Dialog的使用,感兴趣的朋友一起... 目录android中Dialog的使用详解1. 基本Dialog类型1.1 AlertDialog(

浅谈mysql的sql_mode可能会限制你的查询

《浅谈mysql的sql_mode可能会限制你的查询》本文主要介绍了浅谈mysql的sql_mode可能会限制你的查询,这个问题主要说明的是,我们写的sql查询语句违背了聚合函数groupby的规则... 目录场景:问题描述原因分析:解决方案:第一种:修改后,只有当前生效,若是mysql服务重启,就会失效;

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

Android App安装列表获取方法(实践方案)

《AndroidApp安装列表获取方法(实践方案)》文章介绍了Android11及以上版本获取应用列表的方案调整,包括权限配置、白名单配置和action配置三种方式,并提供了相应的Java和Kotl... 目录前言实现方案         方案概述一、 androidManifest 三种配置方式

Android WebView无法加载H5页面的常见问题和解决方法

《AndroidWebView无法加载H5页面的常见问题和解决方法》AndroidWebView是一种视图组件,使得Android应用能够显示网页内容,它基于Chromium,具备现代浏览器的许多功... 目录1. WebView 简介2. 常见问题3. 网络权限设置4. 启用 JavaScript5. D