EARHORNMUSIC UPnP · Android TV · Phones · Android Auto · GNU/Linux
Release 0.5.0

EarhornMediaButtonReceiver.kt

package dev.stave.playback

import android.content.Intent
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
import androidx.media3.session.MediaButtonReceiver
import dev.stave.data.QueuePersistenceStore

/**
 * Maintainer, 2026-10-29: headset / Bluetooth / car Play while Earhorn isn't
 * running. Media3's receiver starts PlaybackService as a FOREGROUND service;
 * if there is nothing to resume the player stays empty, no notification is
 * posted, and Android kills the app with ForegroundServiceDidNotStartInTime.
 * So only start the service when the last saved queue has something playable.
 */
@OptIn(UnstableApi::class)
class EarhornMediaButtonReceiver : MediaButtonReceiver() {
    override fun shouldStartForegroundService(intent: Intent): Boolean {
        // shouldStartForegroundService gets no Context, and onReceive is final;
        // the Application is always created before a receiver runs.
        val app = dev.stave.EarhornApp.instance ?: return false
        return QueuePersistenceStore.hasResumableQueue(app)
    }
}