Merge branch 'feat-fix-stop-close' of github.com:lepre-zhang/Auxio into lepre-zhang-feat-fix-stop-close

This commit is contained in:
Alexander Capehart
2026-01-25 14:49:58 -07:00
8 changed files with 170 additions and 102 deletions
@@ -152,6 +152,11 @@ class AuxioService :
} else {
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
isForeground = false
if (playbackFragment.shouldStopService) {
Timber.d("Exit requested, stopping service")
stopSelf()
}
}
}
}
@@ -37,8 +37,6 @@ import timber.log.Timber as L
interface PlaybackSettings : Settings<PlaybackSettings.Listener> {
/** The action to display on the playback bar. */
val barAction: ActionMode
/** The action to display in the playback notification. */
val notificationAction: ActionMode
/** Whether to start playback when a headset is plugged in. */
val headsetAutoplay: Boolean
/** The current ReplayGain configuration. */
@@ -60,14 +58,13 @@ interface PlaybackSettings : Settings<PlaybackSettings.Listener> {
val pauseOnRepeat: Boolean
/** Whether to maintain the play/pause state when skipping or editing the queue */
val rememberPause: Boolean
/** Whether to always exit when task is removed, even if playing. */
val exitOnTaskRemoval: Boolean
interface Listener {
/** Called when one of the ReplayGain configurations have changed. */
fun onReplayGainSettingsChanged() {}
/** Called when [notificationAction] has changed. */
fun onNotificationActionChanged() {}
/** Called when [barAction] has changed. */
fun onBarActionChanged() {}
@@ -102,12 +99,6 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont
sharedPreferences.getInt(getString(R.string.set_key_bar_action), Int.MIN_VALUE)
) ?: ActionMode.NEXT
override val notificationAction: ActionMode
get() =
ActionMode.fromIntCode(
sharedPreferences.getInt(getString(R.string.set_key_notif_action), Int.MIN_VALUE)
) ?: ActionMode.REPEAT
override val headsetAutoplay: Boolean
get() = sharedPreferences.getBoolean(getString(R.string.set_key_headset_autoplay), false)
@@ -143,6 +134,9 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont
override val rememberPause: Boolean
get() = sharedPreferences.getBoolean(getString(R.string.set_key_remember_pause), false)
override val exitOnTaskRemoval: Boolean
get() = sharedPreferences.getBoolean(getString(R.string.set_key_task_exit), false)
override fun migrate() {
// MusicMode was converted to PlaySong in 3.2.0
fun Int.migrateMusicMode() =
@@ -199,10 +193,6 @@ class PlaybackSettingsImpl @Inject constructor(@ApplicationContext context: Cont
L.d("Dispatching ReplayGain setting change")
listener.onReplayGainSettingsChanged()
}
getString(R.string.set_key_notif_action) -> {
L.d("Dispatching notification setting change")
listener.onNotificationActionChanged()
}
getString(R.string.set_key_bar_action) -> {
L.d("Dispatching bar action change")
listener.onBarActionChanged()
@@ -42,8 +42,6 @@ import org.oxycblt.auxio.music.resolve
import org.oxycblt.auxio.music.resolveNames
import org.oxycblt.auxio.music.service.MediaSessionUID
import org.oxycblt.auxio.music.service.toMediaDescription
import org.oxycblt.auxio.playback.ActionMode
import org.oxycblt.auxio.playback.PlaybackSettings
import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.playback.state.Progression
import org.oxycblt.auxio.playback.state.QueueChange
@@ -65,17 +63,15 @@ private constructor(
private val context: Context,
private val foregroundListener: ForegroundListener,
private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings,
private val bitmapProvider: BitmapProvider,
private val imageSettings: ImageSettings,
private val mediaSessionInterface: MediaSessionInterface,
) : PlaybackStateManager.Listener, ImageSettings.Listener, PlaybackSettings.Listener {
) : PlaybackStateManager.Listener, ImageSettings.Listener {
class Factory
@Inject
constructor(
private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings,
private val bitmapProvider: BitmapProvider,
private val imageSettings: ImageSettings,
private val mediaSessionInterface: MediaSessionInterface,
@@ -85,7 +81,6 @@ private constructor(
context,
foregroundListener,
playbackManager,
playbackSettings,
bitmapProvider,
imageSettings,
mediaSessionInterface,
@@ -102,7 +97,6 @@ private constructor(
fun attach() {
playbackManager.addListener(this)
playbackSettings.registerListener(this)
imageSettings.registerListener(this)
mediaSession.apply {
isActive = true
@@ -121,7 +115,6 @@ private constructor(
fun release() {
bitmapProvider.release()
playbackManager.removeListener(this)
playbackSettings.unregisterListener(this)
imageSettings.unregisterListener(this)
mediaSession.apply {
isActive = false
@@ -159,7 +152,7 @@ private constructor(
PlaybackStateCompat.SHUFFLE_MODE_NONE
}
)
invalidateSecondaryAction()
invalidateNotificationActions()
}
override fun onNewPlayback(
@@ -190,7 +183,7 @@ private constructor(
}
)
invalidateSecondaryAction()
invalidateNotificationActions()
}
// --- SETTINGS OVERRIDES ---
@@ -200,11 +193,6 @@ private constructor(
updateMediaMetadata(playbackManager.currentSong, playbackManager.parent)
}
override fun onNotificationActionChanged() {
// Need to re-load the action shown in the notification.
invalidateSecondaryAction()
}
// --- MEDIASESSION OVERRIDES ---
// --- INTERNAL ---
@@ -334,60 +322,40 @@ private constructor(
// Android 13+ relies on custom actions in the notification.
// Add the secondary action (either repeat/shuffle depending on the configuration)
val secondaryAction =
when (playbackSettings.notificationAction) {
ActionMode.SHUFFLE -> {
L.d("Using shuffle MediaSession action")
PlaybackStateCompat.CustomAction.Builder(
PlaybackActions.ACTION_INVERT_SHUFFLE,
context.getString(R.string.desc_shuffle),
if (playbackManager.isShuffled) {
R.drawable.ic_shuffle_on_24
} else {
R.drawable.ic_shuffle_off_24
},
)
}
else -> {
L.d("Using repeat mode MediaSession action")
PlaybackStateCompat.CustomAction.Builder(
PlaybackActions.ACTION_INC_REPEAT_MODE,
context.getString(R.string.desc_change_repeat),
playbackManager.repeatMode.icon,
)
}
}
state.addCustomAction(secondaryAction.build())
// Add the exit action so the service can be closed
val exitAction =
// Add repeat action
val repeatAction =
PlaybackStateCompat.CustomAction.Builder(
PlaybackActions.ACTION_EXIT,
context.getString(R.string.desc_exit),
R.drawable.ic_close_24,
PlaybackActions.ACTION_INC_REPEAT_MODE,
context.getString(R.string.desc_change_repeat),
playbackManager.repeatMode.icon,
)
.build()
state.addCustomAction(exitAction)
state.addCustomAction(repeatAction)
// Add shuffle action
val shuffleAction =
PlaybackStateCompat.CustomAction.Builder(
PlaybackActions.ACTION_INVERT_SHUFFLE,
context.getString(R.string.desc_shuffle),
if (playbackManager.isShuffled) {
R.drawable.ic_shuffle_on_24
} else {
R.drawable.ic_shuffle_off_24
},
)
.build()
state.addCustomAction(shuffleAction)
mediaSession.setPlaybackState(state.build())
}
/** Invalidate the "secondary" action (i.e shuffle/repeat mode). */
private fun invalidateSecondaryAction() {
L.d("Invalidating secondary action")
/** Invalidate both repeat and shuffle notification actions. */
private fun invalidateNotificationActions() {
L.d("Invalidating notification actions")
invalidateSessionState()
when (playbackSettings.notificationAction) {
ActionMode.SHUFFLE -> {
L.d("Using shuffle notification action")
_notification.updateShuffled(playbackManager.isShuffled)
}
else -> {
L.d("Using repeat mode notification action")
_notification.updateRepeatMode(playbackManager.repeatMode)
}
}
_notification.updateRepeatMode(playbackManager.repeatMode)
_notification.updateShuffled(playbackManager.isShuffled)
if (!bitmapProvider.isBusy) {
L.d("Not loading a bitmap, post the notification")
@@ -427,7 +395,7 @@ private class PlaybackNotification(
addAction(
buildAction(context, PlaybackActions.ACTION_SKIP_NEXT, R.drawable.ic_skip_next_24)
)
addAction(buildAction(context, PlaybackActions.ACTION_EXIT, R.drawable.ic_close_24))
addAction(buildShuffleAction(context, false))
setStyle(
MediaStyle(this).setMediaSession(sessionToken).setShowActionsInCompactView(1, 2, 3)
@@ -486,7 +454,7 @@ private class PlaybackNotification(
*/
fun updateShuffled(isShuffled: Boolean) {
L.d("Applying shuffle action: $isShuffled")
mActions[0] = buildShuffleAction(context, isShuffled)
mActions[4] = buildShuffleAction(context, isShuffled)
}
// --- NOTIFICATION ACTION BUILDERS ---
@@ -18,25 +18,35 @@
package org.oxycblt.auxio.playback.service
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.support.v4.media.session.MediaSessionCompat
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.oxycblt.auxio.AuxioService.Companion.INTENT_KEY_START_ID
import org.oxycblt.auxio.ForegroundListener
import org.oxycblt.auxio.ForegroundServiceNotification
import org.oxycblt.auxio.IntegerTable
import org.oxycblt.auxio.playback.PlaybackSettings
import org.oxycblt.auxio.playback.state.DeferredPlayback
import org.oxycblt.auxio.playback.state.PlaybackStateManager
import org.oxycblt.auxio.playback.state.Progression
import org.oxycblt.auxio.widgets.WidgetComponent
import org.oxycblt.musikr.MusicParent
import org.oxycblt.musikr.Song
import timber.log.Timber as L
class PlaybackServiceFragment
private constructor(
context: Context,
private val context: Context,
private val foregroundListener: ForegroundListener,
private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings,
exoHolderFactory: ExoPlaybackStateHolder.Factory,
sessionHolderFactory: MediaSessionHolder.Factory,
widgetComponentFactory: WidgetComponent.Factory,
@@ -46,6 +56,7 @@ private constructor(
@Inject
constructor(
private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings,
private val exoHolderFactory: ExoPlaybackStateHolder.Factory,
private val sessionHolderFactory: MediaSessionHolder.Factory,
private val widgetComponentFactory: WidgetComponent.Factory,
@@ -56,6 +67,7 @@ private constructor(
context,
foregroundListener,
playbackManager,
playbackSettings,
exoHolderFactory,
sessionHolderFactory,
widgetComponentFactory,
@@ -64,10 +76,73 @@ private constructor(
}
private val waitJob = Job()
private val scope = CoroutineScope(Dispatchers.Main + waitJob)
private var autoStopJob: Job? = null
private val exoHolder = exoHolderFactory.create()
private val sessionHolder = sessionHolderFactory.create(context, foregroundListener)
private val widgetComponent = widgetComponentFactory.create(context)
private val systemReceiver = systemReceiverFactory.create(context, widgetComponent)
private val activityManager =
context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
private val systemReceiver =
systemReceiverFactory.create(
context,
widgetComponent,
onExitRequested = { handleExitRequest() },
)
// Tracks whether an intentional exit has been requested.
private var exitRequested = false
private fun isAppForegrounded(): Boolean {
val processes = activityManager.runningAppProcesses ?: return false
val pkg = context.packageName
val own = processes.find { it.processName == pkg } ?: return false
val imp = own.importance
val visible =
// IMPORTANCE_FOREGROUND (100): Process in foreground UI, user is interacting.
// IMPORTANCE_VISIBLE (200): Process visible, but not in immediate foreground.
imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ||
imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE
L.d("Importance: $imp, visible: $visible")
return visible
}
private fun handleExitRequest() {
val foregrounded = isAppForegrounded()
exitRequested = !foregrounded
L.d("Exit requested: foregrounded=$foregrounded, exitRequested=$exitRequested")
// possibly redundant?
// although endSession() should end up calling scheduleAutoStop() due to
// onProgressionChanged() override, we use it just to be safe, in case it is
// not called if the state was already paused.
scheduleAutoStop()
playbackManager.endSession()
}
private fun scheduleAutoStop() {
autoStopJob?.cancel()
autoStopJob =
scope.launch {
delay(AUTO_STOP_DELAY_MS)
L.d(
"Auto-stop timer expired after ${AUTO_STOP_DELAY_MS / 60000} minutes of inactivity"
)
handleExitRequest()
}
}
private fun cancelAutoStop() {
autoStopJob?.cancel()
autoStopJob = null
}
private fun updateAutoStopTimer(isPlaying: Boolean) {
if (isPlaying) {
cancelAutoStop()
} else if (playbackManager.currentSong != null) {
scheduleAutoStop()
}
}
// --- MEDIASESSION CALLBACKS ---
@@ -77,11 +152,16 @@ private constructor(
widgetComponent.attach()
systemReceiver.attach()
playbackManager.addListener(this)
updateAutoStopTimer(playbackManager.progression.isPlaying)
return sessionHolder.token
}
fun handleTaskRemoved() {
if (!playbackManager.progression.isPlaying) {
val shouldExit =
!playbackManager.progression.isPlaying || playbackSettings.exitOnTaskRemoval
if (shouldExit) {
exitRequested = true
playbackManager.endSession()
}
}
@@ -128,7 +208,11 @@ private constructor(
val notification: ForegroundServiceNotification?
get() = if (exoHolder.sessionOngoing) sessionHolder.notification else null
val shouldStopService: Boolean
get() = exitRequested && !exoHolder.sessionOngoing
fun release() {
autoStopJob?.cancel()
waitJob.cancel()
playbackManager.removeListener(this)
systemReceiver.release()
@@ -137,7 +221,26 @@ private constructor(
exoHolder.release()
}
override fun onNewPlayback(
parent: MusicParent?,
queue: List<Song>,
index: Int,
isShuffled: Boolean,
) {
exitRequested = false
cancelAutoStop()
}
override fun onProgressionChanged(progression: Progression) {
// Update timer whenever play/pause state changes
updateAutoStopTimer(progression.isPlaying)
}
override fun onSessionEnded() {
foregroundListener.updateForeground(ForegroundListener.Change.MEDIA_SESSION)
}
private companion object {
private const val AUTO_STOP_DELAY_MS = 30L * 60L * 1000L
}
}
@@ -41,6 +41,7 @@ private constructor(
private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings,
private val widgetComponent: WidgetComponent,
private val onExitRequested: () -> Unit,
) : BroadcastReceiver() {
private var initialHeadsetPlugEventHandled = false
@@ -50,8 +51,18 @@ private constructor(
private val playbackManager: PlaybackStateManager,
private val playbackSettings: PlaybackSettings,
) {
fun create(context: Context, widgetComponent: WidgetComponent) =
SystemPlaybackReceiver(context, playbackManager, playbackSettings, widgetComponent)
fun create(
context: Context,
widgetComponent: WidgetComponent,
onExitRequested: () -> Unit,
) =
SystemPlaybackReceiver(
context,
playbackManager,
playbackSettings,
widgetComponent,
onExitRequested,
)
}
@Suppress("WrongConstant")
@@ -116,7 +127,7 @@ private constructor(
}
PlaybackActions.ACTION_EXIT -> {
L.d("Received exit event")
playbackManager.endSession()
onExitRequested()
}
WidgetProvider.ACTION_WIDGET_UPDATE -> {
L.d("Received widget update event")
+2 -11
View File
@@ -45,10 +45,11 @@
<string name="set_key_hide_collaborators" translatable="false">auxio_hide_collaborators</string>
<string name="set_key_round_mode" translatable="false">auxio_round_covers</string>
<string name="set_key_bar_action" translatable="false">auxio_bar_action</string>
<string name="set_key_notif_action" translatable="false">auxio_notif_action</string>
<string name="set_key_search_filter_to" translatable="false">KEY_SEARCH_FILTER</string>
<string name="set_key_task_exit" translatable="false">auxio_task_exit</string>
<string name="set_key_songs_sort" translatable="false">auxio_songs_sort</string>
<string name="set_key_albums_sort" translatable="false">auxio_albums_sort</string>
<string name="set_key_artists_sort" translatable="false">auxio_artists_sort</string>
@@ -109,16 +110,6 @@
<item>@integer/action_mode_shuffle</item>
</integer-array>
<integer-array name="entries_notif_action">
<item>@string/set_action_mode_repeat</item>
<item>@string/lbl_shuffle</item>
</integer-array>
<integer-array name="values_notif_action">
<item>@integer/action_mode_repeat</item>
<item>@integer/action_mode_shuffle</item>
</integer-array>
<string-array name="entries_play_in_list_with">
<item>@string/set_play_song_from_all</item>
<item>@string/set_play_song_from_album</item>
+2 -1
View File
@@ -246,7 +246,6 @@
<string name="set_lib_tabs_desc">Change visibility and order of library tabs</string>
<!-- Skip to next (song) -->
<string name="set_bar_action">Custom playback bar action</string>
<string name="set_notif_action">Custom notification action</string>
<string name="set_action_mode_next">Skip to next</string>
<string name="set_action_mode_repeat">Repeat mode</string>
<string name="set_behavior">Behavior</string>
@@ -260,6 +259,8 @@
<string name="set_play_song_by_itself">Play song by itself</string>
<string name="set_keep_shuffle">Remember shuffle</string>
<string name="set_keep_shuffle_desc">Keep shuffle on when playing a new song</string>
<string name="set_task_exit">Always exit on close</string>
<string name="set_task_exit_desc">Stop playback when removed from recents, even if playing</string>
<string name="set_content">Content</string>
<string name="set_content_desc">Control how music and images are loaded</string>
@@ -17,13 +17,6 @@
app:key="@string/set_key_bar_action"
app:title="@string/set_bar_action" />
<org.oxycblt.auxio.settings.ui.IntListPreference
app:defaultValue="@integer/action_mode_repeat"
app:entries="@array/entries_notif_action"
app:entryValues="@array/values_notif_action"
app:key="@string/set_key_notif_action"
app:title="@string/set_notif_action" />
</PreferenceCategory>
<PreferenceCategory android:title="@string/set_behavior">
@@ -50,6 +43,12 @@
app:summary="@string/set_keep_shuffle_desc"
app:title="@string/set_keep_shuffle" />
<SwitchPreferenceCompat
app:defaultValue="false"
app:key="@string/set_key_task_exit"
app:summary="@string/set_task_exit_desc"
app:title="@string/set_task_exit" />
</PreferenceCategory>