You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android MediaPlayer通知在API 33下失效,播放/暂停按钮无法正常工作

Android API 33下媒体通知播放/暂停按钮失效问题

我的Android媒体播放器通知在除API 33(Tiramisu)外的所有版本都能正常工作,但在API 33环境下点击播放/暂停按钮时,日志中出现以下错误:

application is not in focus nor is it a system service for user 0

我已经完成了以下配置:

  • 在AndroidManifest.xml中添加了通知权限:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  • 项目的compileSdkVersion设置为33
  • 针对API 33及以上版本请求了POST_NOTIFICATIONS运行时权限,且已获取授权,权限请求代码如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    if (this.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, PermissionNumber);
    }
}

尽管做了这些操作,媒体播放器通知的按钮还是无法正常响应,请问该如何解决?


解决方案

1. 正确配置媒体会话权限

API 33对媒体按钮的权限校验更严格,仅靠通知权限不够,需确保MediaSession正确声明处理媒体按钮的能力:

MediaSession mediaSession = new MediaSession(context, "MediaPlayerSession");
// 添加必要标志,声明处理媒体按钮和传输控制
mediaSession.setFlags(
    MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
    MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS
);
// 设置回调处理播放/暂停事件
mediaSession.setCallback(new MediaSession.Callback() {
    @Override
    public void onPlay() {
        // 执行播放逻辑
    }

    @Override
    public void onPause() {
        // 执行暂停逻辑
    }
});
// 激活媒体会话
mediaSession.setActive(true);

2. 验证通知的MediaStyle关联

确保通知使用MediaStyle并绑定媒体会话,让系统识别这是媒体类通知:

Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("正在播放")
        .setContentText("歌曲名称")
        .setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
                .setMediaSession(mediaSession.getSessionToken())
                .setShowActionsInCompactView(0, 1)) // 指定紧凑视图显示的按钮索引
        .addAction(R.drawable.ic_pause, "暂停", pausePendingIntent)
        .addAction(R.drawable.ic_play, "播放", playPendingIntent)
        .build();

3. 检查PendingIntent的标志设置

API 30+推荐使用FLAG_IMMUTABLE,同时搭配FLAG_UPDATE_CURRENT确保Intent能正确触发:

Intent playIntent = new Intent(context, MediaPlayerService.class).setAction("ACTION_PLAY");
PendingIntent playPendingIntent = PendingIntent.getService(
        context,
        0,
        playIntent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);

4. 确保媒体服务处于前台状态

API 33对后台服务限制严格,需将媒体服务设为前台:

// 在媒体服务中调用,关联之前创建的通知
startForeground(NOTIFICATION_ID, notification);

5. 添加前台媒体服务权限

在AndroidManifest.xml的服务声明中添加权限:

<service
    android:name=".MediaPlayerService"
    android:permission="android.permission.FOREGROUND_SERVICE_MEDIA" />

内容的提问来源于stack exchange,提问作者صلي علي محمد - Atef Farouk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 16:01:08