使用 PendingIntent 存储应用程序状态的可靠性

Reliability of using a PendingIntent to store application state

我有一个服务首先创建一个新的 Intent,然后调用 setAction('foo')。在此之后我调用 putExtra("key","value123")。然后我调用 PendingIntent.getService(this,999,intent,0)(未传递标志),并将未决意图传递给 AlarmManager。

但是在警报触发之前(或者甚至在之后,似乎)我创建了另一个 Intent 并再次对其调用 setAction('foo'),但不设置任何额外内容。 然后我再次将它传递给 PendingIntent.getService(this,999,intent,0)。但是,这次我在 PendingIntent 上调用 send() 以便立即接收意图。

我观察到的是,原来的额外内容是随新 Intent 一起交付的。我似乎能够一遍又一遍地执行此操作,即使我的应用程序被终止,当我重新启动它时,额外内容仍然存在。

但是,我在文档中没有看到任何具体说明这是否确实是预期行为的内容。这是一种可靠的方法吗?如果我的应用程序被终止,我可以通过它在 RAM 中保留少量数据(仅!)?目前我正在使用 RAMdisk 上的文件,但有些设备显然没有这样的东西。

这就是 PendingIntent 的工作方式 ;-)

第一次调用 PendingIntent.getService() 创建一个新的 PendingIntentrequestCode 设置为 999,Intent 设置为 ACTION="foo"

第二次调用 PendingIntent.getService) 不会创建新的 PendingIntent。它只是 returns 第一个 PendingIntent 的标记(参考)。当您在其上调用 send() 时,将发送原始 PendingIntent

原因是当您调用 PendingIntent.getService() 时,Android 首先尝试找到与您指定的匹配的 PendingIntent。要确定 Intent 是否匹配,它会检查 ACTION、COMPONENT、DATA,还会检查匹配的 requestCode 参数。在您的情况下,对 PendingIntent.getService() 的两次调用都具有相同的 requestCode,并且对 Intent 的调用具有相同的 ACTION。 注意:在确定 Intent 是否匹配 .

时,不考虑 Intent 中的 "extras"

如果您总是想(重新)使用单个 PendingIntent 并在每次使用时覆盖 "extras",您可以将标志 PendingIntent.FLAG_UPDATE_CURRENT 添加到对PendingIntent.getService().

如果您需要并行创建多个 PendingIntent,具有不同的 "extras",您需要确保每次调用 PendingIntent.getService() 时都使用唯一的 requestCode ].