是否可以将 lambda 传递给 Intent?

tom*_*mas 7 lambda serialization android kotlin

我想知道是否可以将 lambda 传递给 kotlin 中的 Intent,因为 lambda 是可序列化的,但是使用这段代码,我在创建 PendingIntent 时遇到错误。

val bundle = bundleOf(ACTION to { pause() })
val playButtonIntent = Intent(this, MusicService::class.java).apply {
        putExtras(bundle)
}
val pendingPlayIntent = PendingIntent.getService(this, 1, playButtonIntent, 0)
Run Code Online (Sandbox Code Playgroud)

错误:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
Run Code Online (Sandbox Code Playgroud)

Jay*_*ard 6

Lambda 本身是可序列化的。但就您而言,它关闭了bundle可能不可序列化的某种类型的变量。因此,它正在创建一个 Lambda 类,其中包含一个用于保存该封闭变量的成员。您无法创建一个可序列化对象,其中包含破坏序列化的内容。

因此,您需要找到一种方法来不保留该捆绑包类,或者需要使其可序列化。

有关更多详细信息,请参阅 SO 中的另一个问题:/sf/answers/3420963171/