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

Flutter audio_service:如何检测音频通知被划走?onNotificationDeleted未触发

问题原因

你的AudioServiceConfig中设置了androidStopForegroundOnPause: true,这会导致音频暂停时,服务自动退出前台状态,此时播放通知不再属于前台服务通知。而onNotificationDeleted回调仅在前台服务通知被用户手动删除时才会触发,后台状态下的通知被划走不会触发该方法。

另外,你配置中的androidNotificationOngoing: true仅对前台服务通知生效——前台时通知无法被划走,暂停后服务退到后台,该限制解除,用户才能划走通知,但此时已无法触发onNotificationDeleted。

解决方案

方案1:保持前台状态(推荐音频场景)

修改AudioServiceConfig,将androidStopForegroundOnPause改为false,这样暂停时服务依然保持前台状态,通知始终是前台服务通知,用户划走时会触发onNotificationDeleted:

config: const AudioServiceConfig(
  androidNotificationChannelId: '...',
  androidNotificationChannelName: 'Audio playback',
  androidNotificationOngoing: true,
  androidStopForegroundOnPause: false, // 修改此处
),

Android 12+对前台服务有严格限制,但音频播放属于系统允许的合法前台服务场景,不会出现权限问题。

方案2:监听后台通知删除事件

如果必须在暂停时退出前台,可以重写AudioHandler的onTaskRemoved方法——当后台服务的通知被用户划走时,系统会调用该回调:

@override
Future<void> onTaskRemoved() async {
  print('Notification deleted while in background!');
  await _player.stop();
  await super.onTaskRemoved();
}

这个方法会在用户删除后台通知、或通过最近任务列表划走应用时触发,适合处理后台状态下的通知删除逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 18:17:24