package de.fojadrachi.playtube import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.ServiceInfo import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Handler import android.os.IBinder import android.os.Looper import android.os.PowerManager import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import androidx.core.app.NotificationCompat import androidx.core.app.ServiceCompat import androidx.core.content.ContextCompat import androidx.media.app.NotificationCompat.MediaStyle import java.net.URL /** * Haelt die App im Hintergrund am Leben (Vordergrunddienst) und zeigt die Medien-Benachrichtigung * samt Sperrbildschirm-Steuerung. Die eigentliche Wiedergabe laeuft in der WebView der * [MainActivity]; der Dienst bekommt den Stand ueber [PlaybackHub] und gibt Befehle dorthin zurueck. */ class PlaybackService : Service() { private lateinit var session: MediaSessionCompat private lateinit var manager: NotificationManager private val main = Handler(Looper.getMainLooper()) private var wakeLock: PowerManager.WakeLock? = null private var artwork: Bitmap? = null private var artworkUrl: String? = null private var notificationKey: List? = null private var metadataKey: List? = null override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { super.onCreate() manager = getSystemService(NotificationManager::class.java) manager.createNotificationChannel( NotificationChannel(CHANNEL_ID, getString(R.string.channel_playback), NotificationManager.IMPORTANCE_LOW), ) session = MediaSessionCompat(this, "Playtube").apply { setCallback(object : MediaSessionCompat.Callback() { override fun onPlay() = PlaybackHub.send(PlayerCommand.Play) override fun onPause() = PlaybackHub.send(PlayerCommand.Pause) override fun onSkipToNext() = PlaybackHub.send(PlayerCommand.Next) override fun onSkipToPrevious() = PlaybackHub.send(PlayerCommand.Previous) override fun onSeekTo(pos: Long) = PlaybackHub.send(PlayerCommand.SeekTo(pos)) }) isActive = true } ServiceCompat.startForeground( this, NOTIFICATION_ID, buildNotification(PlaybackHub.nowPlaying), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK, ) PlaybackHub.listener = ::render render(PlaybackHub.nowPlaying) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { ACTION_PLAY_PAUSE -> PlaybackHub.send(PlayerCommand.PlayPause) ACTION_NEXT -> PlaybackHub.send(PlayerCommand.Next) ACTION_PREVIOUS -> PlaybackHub.send(PlayerCommand.Previous) } return START_NOT_STICKY } override fun onTaskRemoved(rootIntent: Intent?) { stopSelf() } override fun onDestroy() { PlaybackHub.listener = null main.removeCallbacksAndMessages(null) releaseWakeLock() DiscordPresence.shutdown() session.release() super.onDestroy() } // ------------------------------------------------------------------ Anzeige private fun render(info: NowPlaying) { updateArtwork(info.artworkUrl) val metadata = listOf(info.title, info.artist, info.durationMs, artwork != null) if (metadata != metadataKey) { metadataKey = metadata session.setMetadata( MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_TITLE, info.title) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, info.artist) .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, info.durationMs) .apply { artwork?.let { putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, it) } } .build(), ) } session.setPlaybackState(playbackState(info)) val notification = listOf(info.title, info.artist, info.playing, artwork != null) if (notification != notificationKey) { notificationKey = notification manager.notify(NOTIFICATION_ID, buildNotification(info)) } if (info.playing) acquireWakeLock() else releaseWakeLock() DiscordPresence.update(PresencePlan.from(info, System.currentTimeMillis())) } private fun playbackState(info: NowPlaying): PlaybackStateCompat { val state = when { !info.hasTrack -> PlaybackStateCompat.STATE_NONE info.playing -> PlaybackStateCompat.STATE_PLAYING else -> PlaybackStateCompat.STATE_PAUSED } return PlaybackStateCompat.Builder() .setActions( PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or PlaybackStateCompat.ACTION_SEEK_TO, ) .setState(state, info.positionMs, if (info.playing) 1f else 0f) .build() } private fun buildNotification(info: NowPlaying): Notification { val open = PendingIntent.getActivity( this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE, ) val playPauseIcon = if (info.playing) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play val playPauseLabel = getString(if (info.playing) R.string.action_pause else R.string.action_play) return NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(info.title.ifBlank { getString(R.string.notif_idle_title) }) .setContentText(info.artist.ifBlank { getString(R.string.notif_idle_text) }) .setLargeIcon(artwork) .setContentIntent(open) .setOnlyAlertOnce(true) .setOngoing(info.playing) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .addAction(android.R.drawable.ic_media_previous, getString(R.string.action_previous), actionIntent(ACTION_PREVIOUS, 1)) .addAction(playPauseIcon, playPauseLabel, actionIntent(ACTION_PLAY_PAUSE, 2)) .addAction(android.R.drawable.ic_media_next, getString(R.string.action_next), actionIntent(ACTION_NEXT, 3)) .setStyle(MediaStyle().setMediaSession(session.sessionToken).setShowActionsInCompactView(0, 1, 2)) .build() } private fun actionIntent(action: String, requestCode: Int): PendingIntent = PendingIntent.getService( this, requestCode, Intent(this, PlaybackService::class.java).setAction(action), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, ) // ------------------------------------------------------------------ Cover private fun updateArtwork(url: String?) { if (url == artworkUrl) return artworkUrl = url artwork = null if (url == null) return Thread { val bitmap = try { URL(url).openStream().use { BitmapFactory.decodeStream(it) } } catch (_: Exception) { null } main.post { if (artworkUrl == url) { artwork = bitmap render(PlaybackHub.nowPlaying) } } }.start() } // ------------------------------------------------------------------ Wachhalten private fun acquireWakeLock() { if (wakeLock?.isHeld == true) return val power = getSystemService(Context.POWER_SERVICE) as PowerManager wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "playtube:playback") .apply { acquire(WAKE_LOCK_TIMEOUT_MS) } } private fun releaseWakeLock() { wakeLock?.takeIf { it.isHeld }?.release() wakeLock = null } companion object { private const val CHANNEL_ID = "playback" private const val NOTIFICATION_ID = 1 private const val ACTION_PLAY_PAUSE = "de.fojadrachi.playtube.PLAY_PAUSE" private const val ACTION_NEXT = "de.fojadrachi.playtube.NEXT" private const val ACTION_PREVIOUS = "de.fojadrachi.playtube.PREVIOUS" private const val WAKE_LOCK_TIMEOUT_MS = 6 * 60 * 60 * 1000L fun start(context: Context) { ContextCompat.startForegroundService(context, Intent(context, PlaybackService::class.java)) } fun stop(context: Context) { context.stopService(Intent(context, PlaybackService::class.java)) } } }