user3280133
user3280133

Reputation: 10759

Android Notification Action to Start service, intent extra not included

I have a notification that has two actions, Accept and Decline, and the PendingIntent that start a service, RequestUpdaterService. I put extras into the Intent that the PendingIntent gets made from (via PendingIntent#getService). The problem is that when the service is started, the extras aren't in the intent that is passed into Service#onStartCommand.

Notification issuer:

NotificationCompat.Builder n = new NotificationCompat.Builder(context)
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.logo_small)
                .setContentTitle(notification.getText())
                .setContentText(context.getString(R.string.app_name))
                .setContentIntent(getOpenAppPendingIntent())
                .setOngoing(false)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(text));

Intent actionAccept = new Intent(context, UpdateRequestUpdater.class);
actionAccept.putExtra(KeysAndCodes.UPDATE_REQUEST_ID, notificationRequestId);
actionAccept.putExtra(KeysAndCodes.UPDATE_REQUEST_NOTIFICATION_ID, notificationId);
actionAccept.setAction(KeysAndCodes.UPDATE_REQUEST_UPDATER_ACCEPT);

PendingIntent acceptPendingIntent = PendingIntent.getService(context, 0, actionAccept, 0);

Intent actionDecline = new Intent(context, RequestUpdater.class);

actionDecline.putExtra(KeysAndCodes.UPDATE_REQUEST_ID, notificationRequestId);

actionDecline.putExtra(KeysAndCodes.UPDATE_REQUEST_NOTIFICATION_ID, notificationId);
actionDecline.setAction(KeysAndCodes.UPDATE_REQUEST_UPDATER_DECLINE);

PendingIntent declinePendingIntent = PendingIntent.getService(context, 0, actionDecline, 0);

n.addAction(R.drawable.ic_action_accept, getString(R.string.accept_request), acceptPendingIntent);
n.addAction(R.drawable.ic_action_cancel, getString(R.string.decline_request), declinePendingIntent);

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification.getId(), n.build());

RequestUpdaterService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Integer requestId = intent.getIntExtra(KeysAndCodes.UPDATE_REQUEST_ID, 0);
    Integer notificationId = intent.getIntExtra(KeysAndCodes.UPDATE_REQUEST_NOTIFICATION_ID, 0);
...
}

Whenever the RequestUpdaterService is started the requestId and notificationId are always 0. What am I doing wrong?

Upvotes: 4

Views: 2686

Answers (1)

Teo Inke
Teo Inke

Reputation: 5986

Try changing this line:

PendingIntent acceptPendingIntent = PendingIntent.getService(context, 0, actionAccept, 0);

To this:

PendingIntent acceptPendingIntent = PendingIntent.getService(context, 0, actionAccept, PendingIntent.FLAG_UPDATE_CURRENT);

Upvotes: 2

Related Questions