是否可以将lambda传递给Intent?

时间:2018-11-18 17:41:04

标签: android serialization lambda 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)

错误:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object

1 个答案:

答案 0 :(得分:1)

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

因此,您需要找到一种不持有该捆绑软件类的方法,或者需要使其可序列化。

有关更多详细信息,请参见SO中的另一个问题:https://stackoverflow.com/a/48870902/3679676