You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Intent.putExtra传递PendingIntent并解决Gson序列化Notification报错

问题原因

你遇到的报错是因为使用Gson序列化包含Notification对象的自定义类时,Notification内部存在大量CharSequence接口类型的字段,还有PendingIntent这类Android系统专属的Parcelable类型,Gson无法直接序列化/反序列化接口类型和系统复杂类型,因此抛出了找不到无参构造方法的异常。
而且你不需要使用Gson做序列化,Android的Intent原生支持传递Parcelable类型的对象,PendingIntent和Notification本身都实现了Parcelable接口,可以直接通过putExtra传递,完全不需要额外做JSON序列化。

解决方案

直接删除Gson相关逻辑,把需要的参数直接通过Intent传递即可,修改后的代码如下:

1. NotificationService中启动Activity的代码

val i = Intent(this, CAlertWindow::class.java)
i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// 直接传递所需参数,无需Gson序列化
i.putExtra("CONTENT_INTENT", sbn.notification.contentIntent)
i.putExtra("TITLE", title)
i.putExtra("DESC", desc)
// 如果你后续还需要用到Notification的其他字段,也可以直接传递整个Notification对象
// i.putExtra("NOTIFICATION", sbn.notification)
startActivity(i)

2. CAlertWindow中接收参数的代码

// 直接从Intent读取参数,无需Gson解析
val pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    intent.getParcelableExtra("CONTENT_INTENT", PendingIntent::class.java)
} else {
    @Suppress("DEPRECATION")
    intent.getParcelableExtra<PendingIntent>("CONTENT_INTENT")
}
val title = intent.getStringExtra("TITLE")
val desc = intent.getStringExtra("DESC")

alertWindowLayoutBinding.alrTitle.text = title
alertWindowLayoutBinding.alrDesc.text = desc
Log.d("Abdx79/AlertWindow", "In Alert Window")
alertWindowLayoutBinding.alrOpnB.setOnClickListener {
    pendingIntent?.send()
}
alertWindowLayoutBinding.alrDntB.setOnClickListener {
    finish()
}

注意事项

  • 上述代码中针对Android 13(API 33)及以上版本使用了新的Parcelable读取API,避免了过时方法的警告,同时保证了类型安全。
  • 不要使用Gson序列化Android系统的Parcelable类型对象,这类对象的内部结构不适合JSON序列化,用Intent原生的Parcelable传递机制效率更高、兼容性更好。

内容的提问来源于stack exchange,提问作者Abdullah Omer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 20:06:01