Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
The diagnostic gains a power section (battery exemption, power saver, standby bucket, process importance, maker) and logs the screen going off and on while a song plays, with a status line 30 s into the lock (service foreground, locks held, position moving, sound standing still, Spotify page answering); a foreground service that Android refuses to start is now logged instead of swallowed; Samsung phones get a hint under Background playback to add Myspoti to Never sleeping apps, with a row that opens the app's system settings; the refresh loop of the player sleeps while nothing plays instead of waking the main thread every 3 s [skip ci]
kota-zo6d7183517490
diff --git a/base/app/src/main/java/app/myspoti/power/BatteryExemption.kt b/base/app/src/main/java/app/myspoti/power/BatteryExemption.ktindex 35aca303..cf0d0927 100644--- a/base/app/src/main/java/app/myspoti/power/BatteryExemption.kt+++ b/base/app/src/main/java/app/myspoti/power/BatteryExemption.kt@@ -4,6 +4,7 @@ import android.annotation.SuppressLintimport android.content.Contextimport android.content.Intentimport android.net.Uri+import android.os.Buildimport android.os.PowerManagerimport android.provider.Settings@@ -28,6 +29,14 @@ object BatteryExemption {}}+ /** Samsung adds its own sleeping lists on top of Android's: the exemption alone does not always keep the music going. */+ fun isSamsung(): Boolean = Build.MANUFACTURER.equals("samsung", ignoreCase = true)++ /** The app's own system settings page (its battery entry is one tap away); nothing else is opened. */+ fun openAppSettings(context: Context) {+ runCatching { context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))) }+ }+/** Asks once (onboarding, or the first launch after an update); later from Settings. */fun askOnce(context: Context) {val asked = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY_ASKED, false)diff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.ktindex 286ecc91..af3a44f0 100644--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt@@ -46,6 +46,8 @@ object SongPlayer {private const val REMOTE_REFRESH_MS = 3_000L/** How often the state is read again while this phone plays (the page pushes its changes). */private const val LOCAL_REFRESH_MS = 15_000L+ /** Nothing to read (this phone is idle): the refresh loop sleeps this long, or until a state or a Connect device wakes it. */+ private const val IDLE_WAKE_MS = 60_000L/** A song this far past its end with no new state from the page: the state is read at once. */private const val SONG_END_GRACE_MS = 1_500L/** A transport command that has not answered by then is given up (the next one runs). */@@ -253,9 +255,17 @@ object SongPlayer {// AwakeWebView), so reading the whole state and queue every 3 s only kept both processes// awake, screen off. It is read every LOCAL_REFRESH_MS as a safety net, and at once when// the song should have ended without the page saying what came next.+ // With nothing playing and no Connect device, the loop below only found it had nothing to do,+ // every 3 s, waking the main thread: it sleeps then, and a pushed state or a Connect device+ // wakes it (the long timeout is only a net against a missed wake).+ scope.launch { androidx.compose.runtime.snapshotFlow { _activeDevice.value }.collect { refreshWake.trySend(Unit) } }scope.launch {var lastRead = 0Lwhile (true) {+ if (_activeDevice.value == null && !PlaybackService.isRunning && !playing && !isBuffering) {+ kotlinx.coroutines.withTimeoutOrNull(IDLE_WAKE_MS) { refreshWake.receive() }+ continue+ }kotlinx.coroutines.delay(REMOTE_REFRESH_MS)val remote = _activeDevice.value != nullif (!remote && !PlaybackService.isRunning) continue@@ -498,8 +508,12 @@ object SongPlayer {pushNotification(null, boundState?.likeState?.value ?: false)}+ /** Wakes the refresh loop of [attachEngine] when it sleeps: a state was pushed, or a Connect device took over. */+ private val refreshWake = kotlinx.coroutines.channels.Channel<Unit>(kotlinx.coroutines.channels.Channel.CONFLATED)+/** Notification, lock screen, Bluetooth and Android Auto. */private fun pushNotification(song: SongsModel?, liked: Boolean) {+ refreshWake.trySend(Unit)val st = boundState// T4: during an ad break the page reports no track (the song before it would sit there,// buffering), so the notification and the widget say an ad is on instead of that song.diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.ktindex e020bf12..56acc1ef 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt@@ -414,6 +414,13 @@ private fun DataPage(back: () -> Unit) {detail = stringResource(if (exempt) R.string.background_playback_on else R.string.background_playback_off),)}+ // Samsung's "Sleeping apps" is a second list: the app has to be in Never sleeping apps too.+ if (app.myspoti.power.BatteryExemption.isSamsung()) row {+ ImmersiveGroupRow(+ stringResource(R.string.background_playback_open), detail = stringResource(R.string.background_playback_samsung),+ chevron = true, onClick = { app.myspoti.power.BatteryExemption.openAppSettings(ctx) },+ )+ }}}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.ktindex 9a373a58..75bfccba 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt@@ -176,6 +176,14 @@ fun SettingsScreen(navController: NavController) {else app.myspoti.power.BatteryExemption.request(ctx)},)+ // Samsung's "Sleeping apps" is a second list: the app has to be in Never sleeping apps too.+ if (app.myspoti.power.BatteryExemption.isSamsung()) Column(+ Modifier.fillMaxWidth().clickable { app.myspoti.power.BatteryExemption.openAppSettings(ctx) }+ .padding(horizontal = 20.dp, vertical = 10.dp),+ ) {+ Text(stringResource(R.string.background_playback_open), color = AppText, fontSize = 16.sp)+ Text(stringResource(R.string.background_playback_samsung), color = AppMuted, fontSize = 12.sp)+ }}if (tab == 1) {Section(R.string.settings_section_downloads)diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xmlindex b6b7e802..bb7d8ff9 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -47,6 +47,8 @@<string name="background_playback_title">Lecture en arrière-plan</string><string name="background_playback_on">L\'optimisation de la batterie est désactivée : la musique et Spotify Connect continuent écran éteint.</string><string name="background_playback_off">Désactive l\'optimisation de la batterie pour qu\'Android ne mette pas l\'app en pause en arrière-plan.</string>+ <string name="background_playback_samsung">Samsung peut encore mettre Myspoti en veille écran éteint. Ajoutez-le aux « Applications jamais en veille » : Réglages > Batterie > Limites d\'utilisation en arrière-plan.</string>+ <string name="background_playback_open">Ouvrir les réglages de l\'app</string><plurals name="local_files_count"><item quantity="one">%d titre</item><item quantity="other">%d titres</item>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 4abb0782..575b841a 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -47,6 +47,8 @@<string name="background_playback_title">Background playback</string><string name="background_playback_on">Battery optimization is off: music and Spotify Connect keep going with the screen off.</string><string name="background_playback_off">Turn off battery optimization so Android does not pause the app in the background.</string>+ <string name="background_playback_samsung">Samsung can still put Myspoti to sleep with the screen off. Add it to Never sleeping apps: Settings > Battery > Background usage limits.</string>+ <string name="background_playback_open">Open app settings</string><plurals name="local_files_count"><item quantity="one">%d track</item><item quantity="other">%d tracks</item>diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.ktindex 7d073ed4..00d25a2b 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/Logbook.kt@@ -118,6 +118,47 @@ object Logbook {"music volume $v/$max muted=${am.isStreamMute(android.media.AudioManager.STREAM_MUSIC)} mode=${am.mode} output types=$outs"}.getOrNull()+ /**+ * What decides whether Android lets the app run with the screen off: the battery exemption, the+ * standby bucket, the power saver, the process importance, the maker's name (Samsung and others+ * add their own sleeping lists). Music that stops a few seconds after the lock cannot be told+ * apart without them.+ */+ private fun powerLines(context: Context): List<Pair<String, String>> = buildList {+ runCatching {+ val pm = context.getSystemService(android.os.PowerManager::class.java)+ add("exempt" to "ignoring battery optimizations=${pm.isIgnoringBatteryOptimizations(context.packageName)}")+ add("saver" to "power save mode=${pm.isPowerSaveMode} device idle=${pm.isDeviceIdleMode}")+ }+ if (android.os.Build.VERSION.SDK_INT >= 28) runCatching {+ val bucket = context.getSystemService(android.app.usage.UsageStatsManager::class.java).appStandbyBucket+ val name = when (bucket) {+ android.app.usage.UsageStatsManager.STANDBY_BUCKET_ACTIVE -> "active"+ android.app.usage.UsageStatsManager.STANDBY_BUCKET_WORKING_SET -> "working set"+ android.app.usage.UsageStatsManager.STANDBY_BUCKET_FREQUENT -> "frequent"+ android.app.usage.UsageStatsManager.STANDBY_BUCKET_RARE -> "rare"+ android.app.usage.UsageStatsManager.STANDBY_BUCKET_RESTRICTED -> "restricted"+ else -> "other"+ }+ val restricted = context.getSystemService(android.app.ActivityManager::class.java).isBackgroundRestricted+ add("standby" to "bucket $bucket ($name) background restricted=$restricted")+ }+ runCatching {+ val me = android.app.ActivityManager.RunningAppProcessInfo().also { android.app.ActivityManager.getMyMemoryState(it) }+ val importance = when (me.importance) {+ android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND -> "foreground"+ android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE -> "foreground service"+ android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE -> "visible"+ android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE -> "perceptible"+ android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE -> "service"+ android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED -> "cached"+ else -> "other"+ }+ add("process" to "importance ${me.importance} ($importance)")+ }+ add("maker" to "${android.os.Build.MANUFACTURER} ${android.os.Build.MODEL}")+ }+/** The lines the 402 analyses read: refusals, the matrix, registration, clusters, licences, routes, ads. */private val RELEVANT_402 = Regex("""(?i)refus|\b402\b|registration|cluster:|licence|command headers|commands from the page|relay route|relay: |audio after|ad break|page ready|connect/transfer|previous player device""")private const val RELEVANT_LINES = 50@@ -172,6 +213,9 @@ object Logbook {summary.forEach { (k, v) -> appendLine("${k.padEnd(12)}: ${app.myspoti.spotify.report.DiagnosticDigest.mask(v)}") }appendLine()header.forEach { (k, v) -> appendLine("${k.padEnd(12)}: ${app.myspoti.spotify.report.DiagnosticDigest.mask(v)}") }+ appendLine()+ appendLine("--- power ---")+ powerLines(context).forEach { (k, v) -> appendLine("${k.padEnd(12)}: ${app.myspoti.spotify.report.DiagnosticDigest.mask(v)}") }val relevant = tail.filter { RELEVANT_402.containsMatchIn(it.drop(13)) }.takeLast(RELEVANT_LINES)if (relevant.isNotEmpty()) {appendLine()diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.ktindex 973b741c..2011c1c1 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt@@ -186,7 +186,7 @@ class PlaybackService : MediaBrowserServiceCompat() {private fun ensureStarted() {if (foreground) returnrunCatching { androidx.core.content.ContextCompat.startForegroundService(this, Intent(this, PlaybackService::class.java)) }- .onFailure { android.util.Log.w("Myspoti", "service not started from a car command: ${it.message}") }+ .onFailure { Logbook.log("service not started from a car command: ${it.javaClass.simpleName} ${it.message?.take(80)}") }}/** Runs a system command on the app's player; a command with nobody to take it is logged, not lost silently. */@@ -385,11 +385,13 @@ class PlaybackService : MediaBrowserServiceCompat() {.newWakeLock(android.os.PowerManager.PARTIAL_WAKE_LOCK, "Myspoti:playback").apply { setReferenceCounted(false) }.also { cpuLock = it }cpu.acquire(LOCK_TIMEOUT_MS)+ ScreenWatch.start(this)val wifi = wifiLock ?: applicationContext.getSystemService(android.net.wifi.WifiManager::class.java).createWifiLock(android.net.wifi.WifiManager.WIFI_MODE_FULL_HIGH_PERF, "Myspoti:playback").apply { setReferenceCounted(false) }.also { wifiLock = it }if (!wifi.isHeld) wifi.acquire()} else {+ ScreenWatch.stop(this)cpuLock?.takeIf { it.isHeld }?.release()wifiLock?.takeIf { it.isHeld }?.release()}@@ -424,7 +426,7 @@ class PlaybackService : MediaBrowserServiceCompat() {ServiceCompat.startForeground(this, NOTIFICATION_ID, notification,if (Build.VERSION.SDK_INT >= 29) ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK else 0)foreground = true- }+ }.onFailure { Logbook.logEvery("foreground-start", 10_000, "foreground not started: ${it.javaClass.simpleName} ${it.message?.take(80)}") }}private fun build(info: NowPlayingInfo?): Notification {@@ -606,6 +608,18 @@ class PlaybackService : MediaBrowserServiceCompat() {/** True while the service runs (its notification is up): the app may be in the background. */val isRunning: Boolean get() = instance != null+ /** What the service holds, for the screen off / on lines of the diagnostic ([ScreenWatch]). */+ internal fun statusLine(): String {+ val svc = instance+ val c = current+ val service = when { svc == null -> "none"; svc.foreground -> "foreground"; else -> "background" }+ return "service $service, cpu lock held=${svc?.cpuLock?.isHeld}, wifi lock held=${svc?.wifiLock?.isHeld}, " ++ "playing=${c?.playing} buffering=${c?.buffering}"+ }++ /** The position the notification was last given. */+ internal fun statusPosition(): Long = current?.positionMs ?: 0L+private const val PAUSE_GRACE_MS = 60_000L/** A state that did not change is republished at most that often (see [update]). */private const val POSITION_REPUSH_MS = 10_000L@@ -636,7 +650,7 @@ class PlaybackService : MediaBrowserServiceCompat() {// song an extension is still resolving starts right after.if (info.playing || info.buffering) runCatching {androidx.core.content.ContextCompat.startForegroundService(context, Intent(context, PlaybackService::class.java))- }+ }.onFailure { Logbook.logEvery("service-start", 10_000, "service not started for playback: ${it.javaClass.simpleName} ${it.message?.take(80)}") }return}// The player reports several times per second (position, buffering): only a realdiff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ScreenWatch.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ScreenWatch.ktnew file mode 100644index 00000000..d766d093--- /dev/null+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ScreenWatch.kt@@ -0,0 +1,81 @@+package app.myspoti.host.android++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.os.Handler+import android.os.Looper+import android.os.SystemClock+import androidx.core.content.ContextCompat+import kotlinx.coroutines.launch++/**+ * The screen going off and on, in the log, while a song plays: music that stops "30-40 s after the+ * lock" (Samsung, One UI) could not be told from a frozen app, a cut Wi-Fi or a service Android+ * never promoted, because nothing said what the app held at that moment. Registered by+ * [PlaybackService] only while it plays; it logs, it never pauses or restarts anything.+ */+internal object ScreenWatch {+ /** How long after the screen goes off the playback is looked at once more. */+ private const val CHECK_MS = 30_000L++ private val handler = Handler(Looper.getMainLooper())+ private var receiver: BroadcastReceiver? = null+ private var offAt = 0L+ private var positionAtOff = 0L++ fun start(context: Context) {+ if (receiver != null) return+ val r = object : BroadcastReceiver() {+ override fun onReceive(c: Context, intent: Intent) {+ if (intent.action == Intent.ACTION_SCREEN_OFF) off() else on()+ }+ }+ receiver = r+ ContextCompat.registerReceiver(+ context.applicationContext, r,+ IntentFilter().apply { addAction(Intent.ACTION_SCREEN_OFF); addAction(Intent.ACTION_SCREEN_ON) },+ ContextCompat.RECEIVER_NOT_EXPORTED,+ )+ }++ fun stop(context: Context) {+ val r = receiver ?: return+ receiver = null+ handler.removeCallbacks(check)+ offAt = 0L+ runCatching { context.applicationContext.unregisterReceiver(r) }+ }++ private fun off() {+ offAt = SystemClock.elapsedRealtime()+ positionAtOff = PlaybackService.statusPosition()+ Logbook.log("screen off: ${PlaybackService.statusLine()}")+ handler.removeCallbacks(check)+ handler.postDelayed(check, CHECK_MS)+ }++ private fun on() {+ handler.removeCallbacks(check)+ val away = if (offAt > 0) " after ${(SystemClock.elapsedRealtime() - offAt) / 1000} s off" else ""+ offAt = 0L+ Logbook.log("screen on$away: ${PlaybackService.statusLine()}")+ }++ /** Position moving (the notification's), the sound standing still (the watcher's) and the page answering, 30 s into the lock. */+ private val check = Runnable {+ val moved = PlaybackService.statusPosition() - positionAtOff+ val line = "screen off for ${CHECK_MS / 1000} s: ${PlaybackService.statusLine()} position moved ${moved} ms since"+ if (!MyspotiRuntime.isStarted) { Logbook.log("$line, page not started"); return@Runnable }+ MyspotiRuntime.scope.launch {+ val started = SystemClock.elapsedRealtime()+ val answers = runCatching { MyspotiRuntime.spotify.bridge.ping(PING_MS) }.getOrDefault(false)+ val still = runCatching { MyspotiRuntime.spotify.player.stalled.value }.getOrNull()+ val page = if (answers) "answers in ${SystemClock.elapsedRealtime() - started} ms" else "does not answer"+ Logbook.log("$line, sound standing still=$still, Spotify page $page")+ }+ }++ private const val PING_MS = 3_000L+}