我想停止仅在单击活动上的特定按钮后才扩展 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 上的函数从未被调用!!!!为什么?!!!!
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()
正确停止服务。