在API 31(Android 12)上,如果您使用Notification.Builder.addAction()添加操作按钮,则会导致通知不起作用。解决此问题的方法是使用另一种方式添加操作按钮,即使用RemoteInput.Builder添加RemoteInput。以下是示例代码:
RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_REPLY)
.setLabel(replyLabel)
.setChoices(choices)
.setAllowFreeFormInput(true)
.build();
Intent replyIntent = new Intent(this, MyBroadcastReceiver.class);
replyIntent.setAction(ACTION_REPLY);
replyIntent.putExtra(EXTRA_NOTIFICATION_ID, notificationId);
replyIntent.putExtra(EXTRA_CONVERSATION_ID, conversationId);
replyIntent.putExtra(EXTRA_REMOTE_INPUT, remoteInput);
PendingIntent replyPendingIntent =
PendingIntent.getBroadcast(getApplicationContext(),
conversationId,
replyIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Action replyAction = new Notification.Action.Builder(
R.drawable.ic_reply_white_18dp,
replyLabel,
replyPendingIntent)
.addRemoteInput(remoteInput)
.build();
在此示例代码中,我们使用RemoteInput.Builder并在操作按钮上设置RemoteInput。这样就可以在API 31(Android 12)上正常工作通知了。