【发布时间】:2026-01-18 13:20:08
【问题描述】:
所以我有一个服务,在onCreate() 中我设置了 3 个待定意图来启动相同的服务,每个都有不同的额外数据来指定操作。我正在创建一个通知,我想使用一个待定意图作为点击操作,一个作为关闭操作,第三个用于警报。
Intent iCancel = new Intent(this, BootService.class);
Intent iAlarm = new Intent(this, BootService.class);
Intent iDismiss = new Intent(this, BootService.class);
// each will have actions
iAlarm.putExtra(INTENT_ACTION, INTENT_ALARM_FIRED);
iCancel.putExtra(INTENT_ACTION, INTENT_CANCEL);
iDismiss.putExtra(INTENT_ACTION, INTENT_DISMISS);
PendingIntent piCancel = PendingIntent.getService(
this,
0,
iCancel,
Intent.FILL_IN_DATA);
mPiAlarm = PendingIntent.getService(this, 0, iAlarm, Intent.FILL_IN_DATA);
PendingIntent piDismiss = PendingIntent.getService(this, 0, iDismiss, Intent.FILL_IN_DATA);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_action_about)
.setContentTitle(getString(R.string.app_name))
.setContentIntent(piCancel)
.setDeleteIntent(piDismiss);
问题是所有待处理的意图似乎都具有相同的意图额外数据,因此当启动onStartCommand 时,无论是否单击或关闭通知,都会从intent.getIntExtra(INTENT_ACTION) 接收常量INTENT_CANCEL
我相信这与PendingIntent.getService() 中使用的标志有关,我对使用哪个感到困惑。我试过使用PendingIntent.FLAG_CANCEL_CURRENT 和UPDATE_CURRENT,似乎都没有解决问题,但结果不同,我每次操作都会收到INTENT_ALARM_FIRED。
如何让每个待处理的 Intent 拥有自己的 Intent 额外数据?
解决方案
我在PendingIntent 文档中发现了关于这种情况的确切警告。 http://developer.android.com/reference/android/app/PendingIntent.html
刚刚更改了我的请求代码,它可以工作
【问题讨论】:
标签: android service android-notifications