Android 可以在折叠通知中显示操作图标吗?

qba*_*ait 5 android android-notifications

在通知中查看操作的默认行为是展开通知。我可以在不需要扩展它们的情况下显示它们吗?

deL*_*ock 5

是的!:) 您可以在 Android 5.0+ 上(自 API 级别 21 起)。

这是一个工作示例:

 if (Build.VERSION.SDK_INT >= 26)    // Android 8 or later?
 {
     builder = new Notification.Builder (this, Const.NOTIF_CHANNEL_ID);
 }
 else
 {
     builder = new Notification.Builder (this);
 }

 builder.setSmallIcon (R.drawable.ic_notif_icon, 0)
     .setVisibility (Notification.VISIBILITY_PUBLIC)
     .setCategory (Notification.CATEGORY_ALARM)
     .setContentIntent (pendingMainActionIntent)
     .setOngoing (true)
     .addAction (R.drawable.ic_button1, "BUTTON 1", pButton1Intent)
     .addAction (R.drawable.ic_button2, "BUTTON 2", pButton2Intent)
     .addAction (R.drawable.ic_button3, "BUTTON 3", pButton3Intent)
     // Apply the media style template so that we get buttons on the notification widget even when it's in the collapsed mode
     .setStyle (new Notification.MediaStyle ().setShowActionsInCompactView (0, 1, 2));
Run Code Online (Sandbox Code Playgroud)

主要注意最后一行,它确保您想要的:

.setStyle (new Notification.MediaStyle ().setShowActionsInCompactView (0, 1, 2))

另请注意传递给 setShowActionsInCompactView 的参数。例如,如果您只想显示 BUTTON 2 和 BUTTON 3(而不是 BUTTON 1),则可以这样做:

.setShowActionsInCompactView (1, 2) 
Run Code Online (Sandbox Code Playgroud)

在 Android 8.1、Google Pixel 2 和 Samsung S9 上进行了测试,但代码也应该适用于 Android 5-7 和其他手机。享受。

更新:之前的代码仅适用于 Android 8。使其也支持早期版本。builder.setChannelId (Const.NOTIF_CHANNEL_ID)同样在 Android 8 上,您不应该忘记在我发布的代码下方调用。

更新 2:添加了缺失的括号setShowActionsInCompactView并改进了缩进。