Я запускаю службу в onCreate в действии, используя startForegroundService для Android Oreo и выше, и использую startService для более низкой версии, в службе я использовал startForeground в службе, вызывая вспомогательные методы для уведомлений, когда приложение находится на переднем плане, проигрыватель работает отлично и показывает уведомление, но как только я удалил приложение из последних приложений, служба уничтожила. Служба должна продолжать работать как служба переднего плана, но я не знаю, почему она продолжает останавливаться.
Я пробовал некоторые решения, такие как startService, вместо startForegroundService для Oreo и выше, я пробовал другие решения, последнее было перезапуск службы после ее уничтожения, но она работает, но не идеальна.
Я тестирую приложение на Android 13
Вот мой деятельность
class MainActivity : ComponentActivity() {
private var isServiceRunning: Boolean = false
private fun startingService(){
if (!isServiceRunning){
var intent = Intent(this, PlaybackSessionService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
startForegroundService(intent)
}else{
startService(intent)
}
isServiceRunning = true
}
}
@OptIn(UnstableApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
startingService()
//the rest code compose Ui
Вот моя служба PlaybackSessionService
class PlaybackSessionService: MediaSessionService() {
val mediaSession: MediaSession by inject()
val musiCoNotificationManager: MusiCoNotificationManager by inject()
@OptIn(UnstableApi::class)
override fun onCreate() {
super.onCreate()
Log.e("ks","onCreate service")
musiCoNotificationManager.startNotificationService(
mediaSession = mediaSession,
mediaSessionService = this
)
}
@OptIn(UnstableApi::class)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e("ks","onStartCommand service")
musiCoNotificationManager.startNotificationService(
mediaSession = mediaSession,
mediaSessionService = this
)
return super.onStartCommand(intent, flags, startId)
}
override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? {
return mediaSession
}
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
}
override fun onDestroy() {
super.onDestroy()
Log.e("ks","Service destroyed")
mediaSession.apply {
release()
if (player.playbackState != Player.STATE_IDLE){
player.seekTo(0)
player.playWhenReady = false
player.stop()
player.release()
}
}
}
}
Вот мой NotificationManager
class MusiCoNotificationManager(
private val context: Context,
private val player: ExoPlayer,
): KoinComponent {
@UnstableApi
fun startNotificationService(
mediaSessionService: MediaSessionService,
mediaSession: MediaSession
){
buildNotification(mediaSession)
startForegroundNotificationService(mediaSessionService)
}
private fun startForegroundNotificationService(mediaSessionService: MediaSessionService){
Log.e("ks","Enter startForeground fun in MusiCoNotificationManager class ")
val notification = NotificationCompat.Builder(context, MusicoApp.NOTIFICATION_CHANNEL_ID)
.setOngoing(true)
.setOnlyAlertOnce(true)
.build()
mediaSessionService.startForeground(MusicoApp.NOTIFICATION_ID,notification)
}
@UnstableApi
private fun buildNotification(mediaSession: MediaSession){
PlayerNotificationManager.Builder(
context,
MusicoApp.NOTIFICATION_ID,
MusicoApp.NOTIFICATION_CHANNEL_ID
)
.setMediaDescriptionAdapter(
MusiCoNotificationAdapter(context = context, pendingIntent = mediaSession.sessionActivity)
)
.setSmallIconResourceId(R.drawable.music_note)
.build()
.also {
it.setMediaSessionToken(mediaSession.platformToken)
it.setUseFastForwardActionInCompactView(true)
it.setUseNextActionInCompactView(true)
it.setUseRewindActionInCompactView(true)
it.setUsePreviousActionInCompactView(true)
it.setPriority(NotificationCompat.PRIORITY_DEFAULT)
it.setPlayer(player)
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... ecent-apps