Android 13下PlayerNotificationManager无法显示通知求助
Android 13下ExoPlayer PlayerNotificationManager通知不显示的解决思路
针对你遇到的Android 13中后台播放视频通知不显示的问题,结合ExoPlayer和PlayerNotificationManager的特性,整理以下排查和解决方向:
1. 动态申请POST_NOTIFICATIONS权限
Android 13开始POST_NOTIFICATIONS属于运行时权限,仅在Manifest中声明无法生效,必须主动向用户申请:
// 在Activity或Fragment中实现权限请求 private fun requestNotificationPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( requireActivity(), arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_CODE_NOTIFICATION_PERMISSION ) } } }
建议在应用启动或进入播放页面时发起权限申请,用户授权后再初始化PlayerNotificationManager。
2. 适配Android 13前台服务类型要求
Android 13对前台服务的类型做了严格限制,媒体播放场景必须指定mediaPlayback类型:
- 修改Manifest中的服务声明:
<service android:name="com.google.android.exoplayer2.ui.PlayerNotificationManager$MediaNotificationService" android:foregroundServiceType="mediaPlayback" android:exported="false" />
- 初始化PlayerNotificationManager时指定前台服务类型:
playerNotificationManager = PlayerNotificationManager.Builder( getApplication<Application>().applicationContext, 1, EXO_PLAYER_CHANNEL_ID ) .setSmallIconResourceId(R.drawable.racoon) .setMediaDescriptionAdapter(mediaDescriptionAdapter) .setFastForwardActionIconResourceId(R.drawable.ic_forward_10sec) .setRewindActionIconResourceId(R.drawable.ic_replay_10sec) // 新增:指定前台服务类型为媒体播放 .setForegroundServiceType(Service.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK) .build()
3. 调整Player与NotificationManager的关联逻辑
你当前在onResume中调用setPlayer(null)、onStop中关联Player的逻辑,在Android 13的后台限制下可能无法触发前台服务启动:
- Android 13对后台操作的管控更严格,仅在
onStop时关联Player,若此时播放器未处于播放状态,可能不会触发通知显示。 - 建议将关联逻辑与播放状态绑定:
// 当开始播放时 videoViewModel.playerNotificationManager?.setPlayer(videoViewModel.exoPlayer) // 当暂停/停止播放或页面销毁时 videoViewModel.playerNotificationManager?.setPlayer(null)
4. 手动确保通知渠道创建
虽然PlayerNotificationManager会自动创建通知渠道,但Android 13对渠道可见性有新要求,可手动触发创建确保生效:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( EXO_PLAYER_CHANNEL_ID, "媒体播放通知", NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "后台播放视频时显示的控制通知" } val notificationManager = getApplication<Application>().getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(channel) }
5. 升级ExoPlayer版本
旧版本ExoPlayer可能未适配Android 13的通知和前台服务规则,建议升级到最新稳定版(如2.19+),确保API与Android 13兼容。
内容的提问来源于stack exchange,提问作者VikNamin
相关产品推荐
相关产品推荐

