为什么 Android N 在使用 Bundles 时会抛出 TransactionTooLargeException?

Why does Android N throw TransactionTooLargeException when using Bundles?

在 Android N 上,每当我在包中传递一些二进制或大数据时,我都会得到一个 TransactionTooLargeException,但是它在 android M 及以下运行时没有问题。

我该如何解决这个问题?

Android N

中的行为发生了变化

引用 the docs:

Many platform APIs have now started checking for large payloads being sent across Binder transactions, and the system now rethrows TransactionTooLargeExceptions as RuntimeExceptions, instead of silently logging or suppressing them. One common example is storing too much data in Activity.onSaveInstanceState(), which causes ActivityThread.StopInfo to throw a RuntimeException when your app targets Android 7.0.

注意:针对 M 或以下版本的应用不会抛出异常,它们只会静默记录或抑制它们

如何解决:

重新思考为什么您首先需要捆绑这么多数据。

  1. 如果是二进制数据或者位图,最好存储在文件中,在bundle中传递路径

  2. 如果传递的对象太多

    • 您可以使用 OttoEventBus 等库来避免它。

    • 只需再次传递构造对象所需的必要信息。

    • 创建一个单例 class 并在那里设置数据并从那里在另一个 Activity 或片段中访问它。