Android通知操作以启动服务,意图额外未包含。

4
我收到一条通知,其中包含两个操作:接受拒绝,以及一个PendingIntent,用于启动RequestUpdaterService服务。我将额外的信息放入了创建PendingIntent时所使用的Intent中(通过PendingIntent#getService方法)。问题在于,当服务被启动后,传递到Service#onStartCommand方法中的Intent中并没有包含这些额外的信息。
通知发起者:
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);
...
}

每当启动RequestUpdaterService时,requestIdnotificationId总是为0。我做错了什么?
1个回答

2
尝试更改这一行:
PendingIntent acceptPendingIntent = PendingIntent.getService(context, 0, actionAccept, 0);

转换成这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接