Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExoPlayer stops playing in background

I have an application that keeps a global instance of an ExoPlayer instance to facilitate audio streams in the background. After opening lots of apps, the audio stops playing.

It happens as follows:

  • open Activity that starts playing audio
  • press back button to close Activity
  • the audio is still playing and keeps doing so if you leave the device alone (as intended)

However, when you open a dozen or more apps after the last step, the ExoPlayer stops playing at some point. My guess is that a memory cleanup happens and thus ExoPlayer gets deallocated. I tried to get more information from the logs, but that has provided little help so far.

Keeping a reference of the ExoPlayer inside an android.app.Service doesn't make a difference.

The device I am testing on is a Nexus 5 with Android 5.1.x, but the issue happens on other devices too.

I couldn't find a solution in the ExoPlayer documentation pages nor on StackOverflow or Google. Does anyone know the correct way to prevent the ExoPlayer from stopping playback?

like image 832
Byte Welder Avatar asked Dec 21 '15 16:12

Byte Welder


1 Answers

To make sure a Service stays alive as much as possible without being killed by the system, you need to make sure you start it as a foreground service.

This means there will be a notification informing the user of the active service so he can be aware of it. Because of that, you must start the service with a corresponding notification. Here is the example from the docs:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
            System.currentTimeMillis()); 
Intent notificationIntent = new Intent(this, ExampleActivity.class); 
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
notification.setLatestEventInfo(this, getText(R.string.notification_title),
            getText(R.string.notification_message), pendingIntent); 
startForeground(ONGOING_NOTIFICATION_ID, notification);
like image 122
Ricardo Avatar answered Sep 21 '22 22:09

Ricardo