Android 等待启动服务的意向

Android Pending Intent to start service

所以我有一个服务,在 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_CANCEL 是从intent.getIntExtra(INTENT_ACTION)

我相信它与 PendingIntent.getService() 中使用的标志有关,我不知道该使用哪个。我试过使用 PendingIntent.FLAG_CANCEL_CURRENTUPDATE_CURRENT,似乎都没有解决问题,但结果不同,我每次操作都会收到常量 INTENT_ALARM_FIRED

如何让每个待处理的意向都有自己的意向额外数据?

解决方案

我在 PendingIntent 文档中发现了关于这种情况的确切警告。 http://developer.android.com/reference/android/app/PendingIntent.html

刚刚更改了我的请求代码并且有效

这与 Intents 被认为是相同的有关。有关详细信息,请参阅 PendingIntent

解决这个问题的一种方法是改变每个 Intent 的 requestCode。 (getService 调用中的第二个参数)