@@ -13,8 +13,10 @@ import android.content.Intent
13
13
import android.content.ServiceConnection
14
14
import android.os.Build
15
15
import android.os.IBinder
16
+ import androidx.core.app.NotificationCompat
16
17
import androidx.core.app.NotificationManagerCompat
17
18
import androidx.core.app.ServiceCompat
19
+ import androidx.media3.session.DefaultMediaNotificationProvider
18
20
import androidx.media3.session.MediaSession
19
21
import androidx.media3.session.MediaSessionService
20
22
import kotlinx.coroutines.*
@@ -137,6 +139,34 @@ class MediaService : MediaSessionService() {
137
139
}
138
140
}
139
141
142
+ override fun onStartCommand (intent : Intent ? , flags : Int , startId : Int ): Int {
143
+ super .onStartCommand(intent, flags, startId)
144
+ val readerRepository = (application as org.readium.r2.testapp.Application ).readerRepository
145
+
146
+ // App and service can be started again from a stale notification using
147
+ // PendingIntent.getForegroundService, so we need to call startForeground and then stop
148
+ // the service.
149
+ if (readerRepository.isEmpty()) {
150
+ val notification =
151
+ NotificationCompat .Builder (
152
+ this ,
153
+ DefaultMediaNotificationProvider .DEFAULT_CHANNEL_ID
154
+ )
155
+ .setContentTitle(" Media service" )
156
+ .setContentText(" Media service will stop immediately." )
157
+ .build()
158
+
159
+ // Unfortunately, stopSelf does not remove the need for calling startForeground
160
+ // to prevent crashing.
161
+ startForeground(DefaultMediaNotificationProvider .DEFAULT_NOTIFICATION_ID , notification)
162
+ ServiceCompat .stopForeground(this , ServiceCompat .STOP_FOREGROUND_REMOVE )
163
+ stopSelf(startId)
164
+ }
165
+
166
+ // Prevents the service from being automatically restarted after being killed;
167
+ return START_NOT_STICKY
168
+ }
169
+
140
170
override fun onGetSession (controllerInfo : MediaSession .ControllerInfo ): MediaSession ? {
141
171
return binder.session.value?.mediaSession
142
172
}
0 commit comments