Parcelable 和 Bundle
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Parcelable
和 Bundle
对象
可跨进程边界使用,例如与 IPC/Binder 搭配使用
事务、具有 intent 的 activity 之间,以及跨配置存储瞬态状态
更改。本页面提供了有关如何使用
Parcelable
和 Bundle
对象。
注意:Parcel
并非通用型
序列化机制,您不得
将任何 Parcel
数据存储在磁盘上或通过网络发送。
在 Activity 之间发送数据
当应用创建要在其中使用的 Intent
对象时
在启动新 activity 方面startActivity(android.content.Intent)
,
应用可以传入
使用 putExtra(java.lang.String, java.lang.String)
方法。
以下示例代码段演示了如何执行此操作。
Kotlin
val intent = Intent(this, MyActivity::class.java).apply {
putExtra("media_id", "a1b2c3")
// ...
}
startActivity(intent)
Java
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("media_id", "a1b2c3");
// ...
startActivity(intent);
操作系统会将 intent 的基础 Bundle
打包。然后,操作系统会创建
新活动
对数据进行解压缩,并将 intent 传递给新 activity。
我们建议您使用 Bundle
类将操作系统已知的基元设置为
Intent
对象。Bundle
类是高度相关的
针对使用地块进行编组和解组进行了优化。
在某些情况下,您可能需要一种机制来跨 activity 发送复合对象或复杂对象。
在这种情况下,自定义类应实现 Parcelable,并提供适当的
writeToParcel(android.os.Parcel, int)
方法结合使用。
它还必须提供一个名为 CREATOR
的非 null 字段,
实现了 Parcelable.Creator
接口,该接口的
createFromParcel()
方法用于将 Parcel
转换回当前对象。
如需更多信息
请参阅 Parcelable
对象的参考文档。
通过 intent 发送数据时,应注意将数据大小限制为几 KB。
发送过多数据会导致系统抛出
TransactionTooLargeException
异常。
在进程之间发送数据
在进程之间发送数据与在 Activity 之间发送数据类似。但是,在发送
我们建议您不要使用自定义 Parcelable。如果您要发送自定义
Parcelable
对象时,您需要确保
与自定义类完全相同
发送和接收应用上都会显示。通常情况下,这可能是一个通用库
在这两个应用中使用的如果您的应用尝试将自定义 Parcelable 发送到
因为系统无法对其不了解的类进行解组。
例如,应用可能会使用
AlarmManager
类,以及使用自定义 Parcelable
。当闹钟响起时,系统会修改 intent 的
要添加 Bundle
的 extra
进行重复计数这种修改可能会导致系统删除自定义
来自 extra 的 Parcelable
。这种剥离继而会导致应用
在收到修改后的警报 intent 时崩溃,因为应用期望
接收已不存在的额外数据。
Binder 事务缓冲区有固定的固定大小,目前为 1MB,由所有用户共享
处理正在进行的交易由于此上限是在
而非每个 activity 级别,这些事务包括
应用,例如 onSaveInstanceState、startActivity 以及与系统进行的任何交互。当
则抛出 TransactionTooLargeException。
对于 savedInstanceState 这一具体情况,应尽量减少数据量
因为只要用户向用户提供了数据,系统进程便需一直保留提供的数据
导航回该 activity(即使 activity 的进程已终止)。
我们建议您将保存的状态保持在 5 万数据以下。
注意:在 Android 7.0(API 级别 24)及更高版本中,系统会抛出
TransactionTooLargeException 作为运行时异常。
在较低版本的 Android 中,系统仅在 logcat 中显示警告。
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-07-27。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-07-27。"],[],[],null,["# Parcelables and bundles\n\n[Parcelable](/reference/android/os/Parcelable) and [Bundle](/reference/android/os/Bundle) objects are intended to be\nused across process boundaries such as with IPC/Binder\ntransactions, between activities with intents, and to store transient state across configuration\nchanges. This page provides recommendations and best practices for using\n[Parcelable](/reference/android/os/Parcelable) and [Bundle](/reference/android/os/Bundle) objects.\n\n**Note:** [Parcel](/reference/android/os/Parcel) is not a general-purpose\nserialization mechanism, and you should never\nstore any [Parcel](/reference/android/os/Parcel) data on disk or send it over the network.\n\nSending data between activities\n-------------------------------\n\n\nWhen an app creates an [Intent](/reference/android/content/Intent) object to use in\n[startActivity(android.content.Intent)](/reference/android/app/Activity#startActivity(android.content.Intent)) in starting a new Activity,\nthe app can pass in\nparameters using the [putExtra(java.lang.String, java.lang.String)](/reference/android/content/Intent#putExtra(java.lang.String, java.lang.String))\nmethod.\n\nThe following code snippet shows an example of how to perform this operation. \n\n### Kotlin\n\n```kotlin\nval intent = Intent(this, MyActivity::class.java).apply {\n putExtra(\"media_id\", \"a1b2c3\")\n // ...\n}\nstartActivity(intent)\n```\n\n### Java\n\n```java\nIntent intent = new Intent(this, MyActivity.class);\nintent.putExtra(\"media_id\", \"a1b2c3\");\n// ...\nstartActivity(intent);\n```\n\n\nThe OS parcels the underlying [Bundle](/reference/android/os/Bundle) of the intent. Then, the OS creates\nthe new activity,\nun-parcels the data, and passes the intent to the new activity.\n\n\nWe recommend that you use the [Bundle](/reference/android/os/Bundle) class to set primitives known to the OS on\n[Intent](/reference/android/content/Intent) objects. The [Bundle](/reference/android/os/Bundle) class is highly\noptimized for marshalling and unmarshalling using parcels.\n\n\nIn some cases, you may need a mechanism to send composite or complex objects across activities.\nIn such cases, the custom class should implement Parcelable, and provide the appropriate\n[writeToParcel(android.os.Parcel, int)](/reference/android/os/Parcelable#writeToParcel(android.os.Parcel, int)) method.\nIt must also provide a non-null field called `CREATOR` that\nimplements the [Parcelable.Creator](/reference/android/os/Parcelable.Creator) interface, whose\n[createFromParcel()](/reference/android/os/Parcelable.Creator#createFromParcel(android.os.Parcel))\nmethod is used for converting the [Parcel](/reference/android/os/Parcel) back to the current object.\nFor more information,\nsee the reference documentation for the [Parcelable](/reference/android/os/Parcelable) object.\n\n\nWhen sending data via an intent, you should be careful to limit the data size to a few KB.\nSending too much data can cause the system to throw a\n[TransactionTooLargeException](/reference/android/os/TransactionTooLargeException) exception.\n\nSending data between processes\n------------------------------\n\n\nSending data between processes is similar to doing so between activities. However, when sending\nbetween processes, we recommend that you do not use custom parcelables. If you send a custom\n[Parcelable](/reference/android/os/Parcelable) object from one app to another, you need to be certain that the\nexact same version of the custom class is\npresent on both the sending and receiving apps. Typically this could be a common library\nused across both apps. An error can occur if your app tries to send a custom parcelable to\nthe system, because the system cannot unmarshal a class that it has no knowledge of.\n\n\nFor example, an app might set an alarm using\nthe [AlarmManager](/reference/android/app/AlarmManager) class, and use a custom [Parcelable](/reference/android/os/Parcelable)\non the alarm intent. When the alarm goes off, the system modifies the intent's\n[Bundle](/reference/android/os/Bundle) of extras to add\na repeat count. This modification can result in the system's stripping the custom\n[Parcelable](/reference/android/os/Parcelable) from the extras. This stripping, in turn, can result in the app's\ncrashing when it receives the modified alarm intent, because the app expects to\nreceive extra data that is no longer there.\n\n\nThe Binder transaction buffer has a limited fixed size, currently 1MB, which is shared by all\ntransactions in progress for the process. Since this limit is at the process\nlevel rather than at the per activity level, these transactions include all binder transactions in\nthe app such as onSaveInstanceState, startActivity and any interaction with the system. When the size\nlimit is exceeded, a TransactionTooLargeException is thrown.\n\n\nFor the specific case of savedInstanceState, the amount of data should be kept small\nbecause the system process needs to hold on to the provided data for as long as the user\ncan ever navigate back to that activity (even if the activity's process is killed).\nWe recommend that you keep saved state to less than 50k of data.\n\n\n**Note:** In Android 7.0 (API level 24) and higher, the system throws a\nTransactionTooLargeException as a runtime exception.\nIn lower versions of Android, the system only shows a warning in logcat."]]