使用Android L Notification.MediaStyle添加终止播放按钮

lim*_*lim 16 android android-notifications android-mediaplayer android-5.0-lollipop

我想使用新的Android L MediaStyle模板创建媒体播放通知.现在,我成功完成了以前,播放,暂停,下一步等操作(通过使用addAction(),但我无法找到添加"关闭"按钮的方法,如Android Notifications Documentation屏幕截图中所示:

在此输入图像描述

有没有一种巧妙的方法来实现这一目标?我希望"关闭"按钮终止当前正在播放的播放,清除播放通知,并按照附带的屏幕截图进行定位.

mat*_*ash 13

UPDATE

使用支持库的此通知样式的版本时,即NotificationCompat.MediaStylesetShowCancelButton()按钮.

这将添加关闭按钮,但仅限于Lollipop之前的版本,以解决在显示为前台服务的一部分后无法被忽略的通知的错误.

在Lollipop中,首选选项是能够解除通知(当音频暂停时),而不是使用自定义按钮来执行此操作.


老答复

通过查看Notification.MediaStyle类的源代码,似乎目前在MediaStyle通知样式中不支持这样的按钮:

    private RemoteViews makeMediaBigContentView() {
        final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
        RemoteViews big = mBuilder.applyStandardTemplate(getBigLayoutResource(actionCount),
                false /* hasProgress */);

        if (actionCount > 0) {
            big.removeAllViews(com.android.internal.R.id.media_actions);
            for (int i = 0; i < actionCount; i++) {
                final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i));
                big.addView(com.android.internal.R.id.media_actions, button);
            }
        }
        styleText(big);
        hideRightIcon(big);
        applyTopPadding(big);
        big.setViewVisibility(android.R.id.progress, View.GONE);
        return big;
    }
Run Code Online (Sandbox Code Playgroud)

这与它膨胀的布局匹配(notification_template_material_big_media),其中包含:

  • 媒体图像的布局.
  • 三个文本行的LinearLayout.
  • 添加媒体操作的LinearLayout.
  • ImageView显示这两者之间的分隔线.

但没有别的.

文档页面中的关闭按钮似乎只是艺术家的演绎(Google Play音乐也不包括它).


Ank*_*wal 7

添加到@matiash 的答案:

  1. 对于 Pre-Lollipop,他的回答是必要的。

    notificationBuilder.setStyle(new NotificationCompat.MediaStyle().setShowCancelButton(true).setCancelButtonIntent(createPlayIntent());
    
    Run Code Online (Sandbox Code Playgroud)
  2. 对于后棒棒糖:要启动媒体播放器的通知必须有一定使用startForeground()启动媒体服务的Foreground Service。现在的问题是,这Service是不可忽视的。即使我们设置了setOngoing(false).

遵循的最佳实践是使服务在暂停状态下可关闭。为此,当您的媒体服务收到暂停状态回调时,请调用stopForeground(false). 这会停止服务,但保持通知有效。它现在可以被驳回。

快乐编码。