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

Android 14:音频播放通知无法按预期设置为不可滑动问题求助

解决Android 14中AudioService通知滑动清除问题

问题分析

你的初始化配置中androidNotificationOngoing: true是固定值,无法随播放状态动态切换;同时Android 14对前台服务通知的管理逻辑有调整,单纯依赖初始化配置无法实现播放/暂停时通知清除权限的动态变化。

解决方案

1. 调整AudioService初始化配置

将androidNotificationOngoing设为false,后续通过播放状态动态控制该属性:

audioHandler = await AudioService.init(
  builder: () => AudioPlayerHandler(),
  config: const AudioServiceConfig(
    androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
    androidNotificationChannelName: 'Audio playback',
    androidNotificationOngoing: false, // 改为false,后续动态切换
    androidStopForegroundOnPause: true,
  ),
);

2. 在AudioPlayerHandler中动态修改通知属性

重写play()和pause()方法,根据播放状态切换通知的ongoing属性(true表示不可清除,false表示可清除):

class AudioPlayerHandler extends BaseAudioHandler with QueueHandler, SeekHandler {
  // 保留你已有的播放器初始化、队列管理等逻辑

  @override
  Future<void> play() async {
    // 执行原生播放逻辑
    await super.play();
    
    // 将通知设为不可清除(ongoing: true)
    if (AudioService.androidAudioHandler != null) {
      final currentNotification = await AudioService.androidAudioHandler!.getNotification();
      if (currentNotification != null) {
        await AudioService.androidAudioHandler!.setNotification(
          currentNotification.copyWith(ongoing: true),
        );
      }
    }

    // 更新服务状态为播放中,保持前台服务
    await AudioServiceBackground.setState(
      controls: [MediaControl.pause, MediaControl.stop],
      systemActions: const {MediaAction.seekTo},
      playing: true,
      processingState: ProcessingState.ready,
    );
  }

  @override
  Future<void> pause() async {
    // 执行原生暂停逻辑
    await super.pause();
    
    // 更新服务状态为暂停,退出前台服务(因androidStopForegroundOnPause: true)
    await AudioServiceBackground.setState(
      controls: [MediaControl.play, MediaControl.stop],
      systemActions: const {MediaAction.seekTo},
      playing: false,
      processingState: ProcessingState.ready,
    );

    // 将通知设为可清除(ongoing: false)
    if (AudioService.androidAudioHandler != null) {
      final currentNotification = await AudioService.androidAudioHandler!.getNotification();
      if (currentNotification != null) {
        await AudioService.androidAudioHandler!.setNotification(
          currentNotification.copyWith(ongoing: false),
        );
      }
    }
  }
}

原理说明

  • 播放时:通过setNotification将通知设为ongoing: true,同时保持前台服务状态,确保通知无法滑动清除。
  • 暂停时:因androidStopForegroundOnPause: true,服务会自动退出前台,此时重新设置通知为ongoing: false,让通知可以被滑动清除。

内容的提问来源于stack exchange,提问作者niclas_4

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 11:42:32