gpt4 book ai didi

android - 如果强制关闭目标应用程序,PendingIntent 会发生什么情况?

转载 作者:行者123 更新时间:2023-11-30 05:04:23 27 4
gpt4 key购买 nike

我实际上正在开发一个应在未来 5 天后发布通知的应用。

我使用 AlarmManager 将 PendingIntent 发送到我的 Receiver 类。一切正常,直到我强行关闭我的应用程序。在这种情况下,通知不会出现。

所以我的问题是:已触发但未达到目标的 PendingIntent 会怎样?当我的应用程序最终重新启动时,我可以检查未达到目标的 PendingIntents 吗?

编辑 1:

这些是我的广播接收器的基本部分:

    override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent?.action != null) {
when (intent.action) {
INTENT_ACTION_BOOT_COMPLETED -> handleDeviceBoot()
INTENT_ACTION_REMINDER -> handleReminder(context, intent.getLongExtra(EXTRA_ITEM_ID, -1))
}
}
}

private suspend fun schedule(context: Context, itemId: Long, fireDate: LocalDateTime) = withContext(Dispatchers.IO) {
AlarmManagerCompat.setAndAllowWhileIdle(
getAlarmManager(context),
AlarmManager.RTC,
fireDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(),
makePendingIntent(context, itemId)
)

with(AppDatabase.get(context).reminderDao()) {
val oldReminder = getItemReminder(itemId)

if (oldReminder == null) {
insert(Reminder(itemId = itemId, fireDate = fireDate))
} else {
update(Reminder(id = oldReminder.id, itemId = itemId, fireDate = fireDate))
}
}
}

private suspend fun cancel(context: Context, itemId: Long) = withContext(Dispatchers.IO) {
val reminderDao = AppDatabase.get(context).reminderDao()
val reminder = reminderDao.getItemReminder(itemId)

reminder?.let {
getAlarmManager(context).cancel(makePendingIntent(context, itemId))
reminderDao.delete(it)
}
}

private fun getAlarmManager(context: Context) = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

private fun makePendingIntent(context: Context, itemId: Long): PendingIntent {
val alarmIntent = Intent(context, ReminderManager::class.java).apply {
action = INTENT_ACTION_REMINDER
putExtra(EXTRA_ITEM_ID, itemId)
}
return PendingIntent.getBroadcast(context, itemId.toInt(), alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}

最佳答案

定义见Official Android Documentation

PendingIntent 本身只是对系统维护的 token 的引用,该 token 描述了用于检索它的原始数据。这意味着,即使它拥有的应用程序的进程被终止,PendingIntent 本身仍可从已获得它的其他进程中使用。如果创建应用程序稍后重新检索相同类型的 PendingIntent(相同的操作、相同的 Intent 操作、数据、类别和组件以及相同的标志),它将收到表示相同标记的 PendingIntent(如果它仍然有效),并且可以因此调用 cancel() 将其删除。

重新访问您的代码以检查是否有任何其他原因会导致此问题。

关于android - 如果强制关闭目标应用程序,PendingIntent 会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821741/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com