Michau
Michau

Reputation: 1

Flutter audio_service: Notification does not disappear

I am developing an application which allows the user to browse a collection of ebooks, pick one and then decide to read it or listen to it. It is also possible to switch between reading and listening. Therefore there are separate views for listening, reading or browsing audiobooks.

I am using Flutter plugins: audio_service and just_audio to implement audiobook playback. During app unit, I create my own AudioHandler as folows:

class AudioHandler extends BaseAudioHandler with SeekHandler {
  static final AudioHandler _singleton = AudioHandler._();

  static Future<void> init() async {
    var audioService = await AudioService.init(
      builder: () => AudioHandler(),
      config: const AudioServiceConfig(
        androidNotificationChannelId: 'nl.dropcatcher.sermons.channel.audio',
        androidNotificationChannelName: 'Sermon playback',
        androidStopForegroundOnPause: false,
        fastForwardInterval: Duration(seconds: 10),
        rewindInterval: Duration(seconds: 10),
      ),
    );
    audioService.playbackState.add(PlaybackState(
      controls: [
        MediaControl.pause,
      ],
      systemActions: const {
        MediaAction.seek,
        MediaAction.seekForward,
        MediaAction.seekBackward,
      },
      androidCompactActionIndices: const [0],
      processingState: AudioProcessingState.buffering,
      playing: false,
      updatePosition: Duration.zero,
      bufferedPosition: Duration.zero,
      speed: 1.0,
      queueIndex: 0,
    ));
  }

  factory AudioHandler() {
    return _singleton;
  }
  AudioHandler._();
}

Then in the audiobook player view, I use the AudioPlayer to play the actual audiobook and dispose it when the view is closed:

class _SermonPlayerState extends State<_SermonPlayerWidget> {
  final AudioPlayer player = AudioPlayer();

  @override
  void initState() {
    // ...
    player.play();
  }
 
  @override
  void dispose() {
    // ...
    AudioHandler().stop();
    player.dispose();
    super.dispose();
  }
}  

However, the Android notification with the player control buttons (created by audio_service when the AudioPlayer starts playing) persists after dispose(), even though it is no longer applicable. In fact, it even persists when I reload the app from the Flutter debugger. What is more perplexing is that in the Web version, it works - as soon as the AudioPlayer is disposed, the browser notification with player buttons disappears.

I can't see any API to programmatically hide the notification. So how do I get rid of it when the user is no longer on the audio player page?

Upvotes: 0

Views: 111

Answers (0)

Related Questions