Search code examples
androidkotlinserviceandroid-mediaplayer

Playing an audio file in the background with Service


I am trying to set up an Android app with Kotlin. It should be able to play an audio file in the background. For that I use Service.

For now the service is fired up to play the audio file, from the onStop() method of the main activity.

So when I send the app to the background, the sound playing starts.

This works except that the play of the audio file only lasts for about 11 seconds instead of playing the whole file.

The AndroidManifest.xml contains the following lines:

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

The code firing up the service looks like this:

val serviceIntent = Intent(this, AudioService::class.java)
serviceIntent.putExtra("audioPath", audioPath);
startForegroundService(serviceIntent)

The code for the service looks like this:

class AudioService: Service() { private lateinit var audioPlayer: MediaPlayer

override fun onCreate() {
    super.onCreate()
}


override fun onBind(p0: Intent?): IBinder? {
    return null
}


override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    .....
}

}

Since the audio playing starts, what I did is obviously not totally wrong. But what is missing for it to finish?


Solution

  • You can keep a service running indefinitely, by promoting your service to a "foreground service". You can only become a foreground service by adding a Notification for the service to the notifications area.

    As written above you need to use startForeground(int,Notification) method to aware user about your service. It also get more privilage for it.

    You can read more about it here (example inside).