android - 在组件和应用程序之间传递数据

标签 android android-intent memory-management bundle parcelable

在 Android 的组件和应用程序之间传递数据的方式有很多种。例如,这里有一些:

Intent intent = new Intent(this, DestinationActivity.class);
intent.putExtra("key", "value");

or

Bundle args = new Bundle();
args.putInt("someInt", someInt);
args.putParcelable("key", ParcelableObject);
Intent intent = new Intent();
intent.setAction("someAction");
intent.putExtra("key", arg);

or

fragment.setArguments(args);

据我所知,在 Java 中原始值存储在堆栈中,而对象则放在堆中。所以,我想知道当我们调用这些方法时发生了什么:安卓。

最佳答案

实际上并没有那么多事情发生。 Bundle 内部是一个 Map。 putInt 会将整数原语转换为 Integer 对象,并将 Integer 放入映射中。 putString 会将 String 对象放在那里。 putParcelable 会将扩展 Parcelable 的对象放入 map 中。这就是当时发生的一切。

调用 startActivity 时,它将遍历该 map ,并基本上构建数据流。该格式不是 JSON,但它有类似的用途 - 它是一种易于理解的格式,可以在以后解析为值。当它遍历该 map 时,它知道如何向该文件添加基元(int、double 等)。它还知道如何处理字符串。对于 Parcelable 对象,对象中有一个函数可以将对象添加到流中,还有一个函数可以将其从流中解析出来。然后它获取该流并要求操作系统将该流传递给实现 Intent 的进程。该应用程序中的 Android 框架会将流解析回 map (创建新对象),然后将其传递给 onCreate。

为什么这一切有效?因为你运行的 Intent 可能不在你的过程中。所以它不能直接共享它们,它需要制作副本。 extras 只是一种内置的序列化方法,可以轻松传递复杂数据。

为什么有时用Bundle,有时用Intent?好吧,每个 Intent 里面都有一个 Bundle。调用 intent.putIntExtra 将在该 Intent 内的 bundle 上调用 Bundle.putInt。它只是一种方便的方法,因此您无需调用 intent.getExtras().putInt()。

关于android - 在组件和应用程序之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47124966/

相关文章:

android - 只能使用 releaseImplementation 和 debugImplementation 从 maven 添加 Kotlin Multiplatform Mobile 库

java - 使用 SQLiteOpenHelper 时 ContextWrapper.openOrCreateDatabase 中的 NullPointerException

android - 可选择启动 Activity 并使用来自 Android 服务的通知。仅在存在某个应用程序时启动或通知

c++ - 奇怪的 malloc 行为不允许在 64 位进程上分配超过 2GB 的内存

java - VisualVM 堆大小不遵循已用大小

javascript - 如何删除 Android WebView 中的标题? (加载时)

android - 如何判断代码是否需要在 UI 线程上运行

android - Android 系统是在一个进程中向多个接收者多次发送 BOOT_COMPLETED Intent 还是只发送一次?

android - 将第 3 方 Android JAR 集成到 Titanium Mobile 应用程序中?

排除因内存导致的 iPhone/iPad 设备崩溃问题