From the course: Concurrent Programming with Android: Threads, Workers, and Kotlin Coroutines

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

Play audio in a service with MediaPlayer

Play audio in a service with MediaPlayer

- [Instructor] One of the most common uses of a foreground service is to play audio. A bound services API is exposed to the activity that binds to it, so you can control its functions from the user interface. But by turning the service into a foreground service, you're pretty much guaranteeing it will stick around. First of all, in this version of the application in this branch, I've added an audio file to an assets directory under the app module. And in the constant's class, I've created a constant named AUDIO_FILE that has the name of that file. Now in the MyService class, I'm going to refactor this. So instead of just doing something, I'm going to start some music. I've press Shift + F6 for refactoring and renaming, and I'll rename this function to startMusic. To play the music, I'll need a MediaPlayer object and I'll declare this as a property of the service. It'll be private to the service and it will be a…

Contents