首页 文章

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

提问于
浏览
16

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

enter image description here

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

3 回答

  • 1

    UPDATE

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

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

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


    OLD ANSWER

    通过查看 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;
        }
    

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

    • 媒体图像的布局 .

    • 三个文本行的LinearLayout .

    • 添加媒体操作的LinearLayout .

    • ImageView显示这两者之间的分隔线 .

    但没有别的 .

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

  • 1

    那是你正在寻找的取消按钮:

    .setShowCancelButton(true)
      .setCancelButtonIntent(stopPendingIntent)
    

    在您的MediaStyle实例上 .

  • 13

    添加到@ matiash的答案:

    • 对于Pre-Lollipop,他的回答是必要的 .
    notificationBuilder.setStyle(new NotificationCompat.MediaStyle().setShowCancelButton(true).setCancelButtonIntent(createPlayIntent());
    
    • 对于post-Lollipop:要启动媒体播放器通知,必须确保使用 startForeground()Foreground Service 启动媒体服务 . 现在的问题是这个 Service 是不允许的 . 即使我们设置 setOngoing(false) .

    遵循的最佳做法是使服务在暂停状态下被拒绝 . 为此,当您的媒体服务收到暂停状态回调时,请调用 stopForeground(false) . 这会停止服务,但会使通知保持活动状态 . 它现在可以被驳回 .

    快乐的编码 .

相关问题