Search code examples
androidflutterjust-audio

Flutter just_audio abruptly stops when in the background after around 10 minutes


I'm using just_audio for my app and I have done the following:

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

In AndroidManifest and this in my lib,

  AudioPlayer audioPlayer = AudioPlayer();
  final playlist = ConcatenatingAudioSource(
    useLazyPreparation: true,
    shuffleOrder: DefaultShuffleOrder(),
    children: [
      AudioSource.uri(Uri.file("$path/$fileName")),
      AudioSource.uri(Uri.parse("${Constants.soundsLocation}silence.mp3")),
    ],
  );
  await audioPlayer.setAudioSource(playlist,
      initialPosition: Duration.zero);
  audioPlayer.setLoopMode(LoopMode.all);
  audioPlayer.setVolume(1);
  audioPlayer.setSpeed(1);
  audioPlayer.play();

It's usually a 10 second audio, followed by 1 second of silence on loop. It works properly on IOS, but on Android, if the app is in the background it shuts down after about 10 minutes and I get Lost connection to device. on VSCode.

I suspected that the connection shutdown might have been caused by Doze Mode in Android, but I used this command: adb shell dumpsys deviceidle force-idle to enforce doze mode and the app didn't shut down. It shut down after 10~ minutes as usual. Looking for any guidance on how to tackle this. I'm testing on a Simulator, but people have reported this on their phones too.

I also tried running it in debug mode and put a break point on all exceptions, but nothing gets triggered when the app shuts down.

EDIT I did some digging and checked the Logcat, getting this before crash: I/ActivityManager: Killing 25231:com.appname.app/u0a158 (adj 700): excessive cpu 220780 during 300021 dur=548815 limit=25


Solution

  • It is normal for Android to kill your app after 10 minutes when it is in the background, unless there's a foreground service running, and to get one of those, it is not enough to only declare "permission" to use a foreground service in the manifest, you also need to actually declare a service, and write the code for the service.

    The just_audio README mentions two ways of achieving this (if you search the README for the word "background"):

    1. Use the audio_service package. This lets you write your own service to your own liking.
    2. Use the just_audio_background package (easier for beginners). This provides a ready-made service for you.

    If your app has simple requirements and can work using a single player instance, I suggest you use the just_audio_background package and follow the setup steps. You'll notice that it gives you the code you'll need to copy and paste into your manifest file, and also gives you the Dart code you'll need to copy and paste into your Flutter app code.