如何停止 MediaLibraryService:media3 android

问题描述 投票:0回答:1

我想停止仅在单击活动上的特定按钮后才扩展 MediaLibrarySession 的前台服务,所以我尝试了:

val serviceIntent = Intent(this@PartyHostActivity, PlayerService::class.java)
stopService(serviceIntent)

val serviceIntent = Intent(this@PartyHostActivity, PlayerService::class.java)
startService(serviceIntent)
stopService(serviceIntent)

但是他们都没有停止服务,

onDestroy
MediaLibraryService 上的函数从未被调用!!!!为什么?!!!!

android kotlin foreground-service android-media3
1个回答
0
投票

stopService()
方法可能不会立即停止服务

在前台服务的情况下,您需要在服务代码中显式调用

stopForeground(true)
以从前台删除服务并允许其停止。这将在您的
onDestroy()
中触发
MediaLibraryService
方法。

在你的活动中:

// Start the service
val serviceIntent = Intent(this@PartyHostActivity, PlayerService::class.java)
startService(serviceIntent)

// Stop the service when the specific button is clicked
specificButton.setOnClickListener {
    val stopIntent = Intent(this@PartyHostActivity, PlayerService::class.java)
    stopIntent.action = "STOP_SERVICE"
    startService(stopIntent)
}

在你的

MediaLibraryService

class PlayerService : Service() {
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent?.action == "STOP_SERVICE") {
            // Stop the foreground service and allow it to be stopped
            stopForeground(true)
            stopSelf()
        } else {
            // Start the foreground service
            // Perform other necessary operations
        }
        return START_STICKY
    }
    // override other functions as you wish

}

通过发送带有动作“STOP_SERVICE”的意图,您可以将停止服务的请求与其他启动请求区分开来。在

onStartCommand()
方法中,您检查此操作,然后调用
stopForeground(true)
stopSelf()
正确停止服务。

© www.soinside.com 2019 - 2024. All rights reserved.