Skip to content

Commit

Permalink
Fix NullPointerException crash when starting PlaybackService from onS…
Browse files Browse the repository at this point in the history
…tartCommand directly (#83)
  • Loading branch information
mr3y-the-programmer authored Aug 24, 2024
1 parent 8a1ba62 commit 4d2fb4b
Showing 1 changed file with 27 additions and 16 deletions.
43 changes: 27 additions & 16 deletions app/src/main/kotlin/com/mr3y/podcaster/service/PlaybackService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -42,25 +42,12 @@ class PlaybackService : MediaSessionService() {

override fun onCreate() {
super.onCreate()
val audioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_SPEECH)
.setUsage(C.USAGE_MEDIA)
.build()
val mediaSourceFactory = ProgressiveMediaSource.Factory(DownloadMediaService.buildCacheDataSourceFactory(this))
val audioOnlyRenderersFactory = RenderersFactory { handler, _, audioListener, _, _ ->
arrayOf(MediaCodecAudioRenderer(this, MediaCodecSelector.DEFAULT, handler, audioListener))
}
val player = ExoPlayer.Builder(this, audioOnlyRenderersFactory, mediaSourceFactory)
.setAudioAttributes(audioAttributes, true)
.setHandleAudioBecomingNoisy(true)
.build()
mediaSession = MediaSession.Builder(this, player)
.setCallback(PlaybackMediaSessionCallback())
.build()
getOrCreateMediaSessionInstance()
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
mediaPlayer = ServiceMediaPlayer(mediaSession!!.player, podcastsRepository)
val currentSession = getOrCreateMediaSessionInstance()
mediaPlayer = ServiceMediaPlayer(currentSession.player, podcastsRepository)
mediaPlayer.attachPlayerListener()
mediaPlayer.startListeningForUpdatesIn(serviceScope)
return super.onStartCommand(intent, flags, startId)
Expand All @@ -82,6 +69,30 @@ class PlaybackService : MediaSessionService() {

override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = mediaSession

private fun getOrCreateMediaSessionInstance(): MediaSession {
return mediaSession ?: run {
val audioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_SPEECH)
.setUsage(C.USAGE_MEDIA)
.build()
val mediaSourceFactory = ProgressiveMediaSource.Factory(DownloadMediaService.buildCacheDataSourceFactory(this))
val audioOnlyRenderersFactory = RenderersFactory { handler, _, audioListener, _, _ ->
arrayOf(MediaCodecAudioRenderer(this, MediaCodecSelector.DEFAULT, handler, audioListener))
}
val player = ExoPlayer.Builder(this, audioOnlyRenderersFactory, mediaSourceFactory)
.setAudioAttributes(audioAttributes, true)
.setHandleAudioBecomingNoisy(true)
.build()

MediaSession.Builder(this, player)
.setCallback(PlaybackMediaSessionCallback())
.build()
.also {
mediaSession = it
}
}
}

private fun release() {
mediaSession?.run {
player.release()
Expand Down

0 comments on commit 4d2fb4b

Please sign in to comment.