I have a started and bounded service (music player) and I want to stop it when the notification's close button is clicked. however, the service will not be stopped if there are activities bounded to it. How can I stop service when the button is clicked?
I have tried gathering a list of activities in service and calling the callback to them to unbind (actually finish()
which then on onStop()
will call unbind()
) and then I stop the service by calling stopSelf()
but I don't think it a good idea because lifecycle issues and some activities being added multiple times and maintaining the list is hard . There SHOULD be a better way! though I haven't found anything after searching for hours.
here is my PlayerService
's onStartCommand()
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
info("Starting Player Service ...")
started=true
if (intent == null) {
error("intent was null")
pause()
return START_STICKY
}
if (intent.hasExtra(KEY_SONGS)) {
if(intent.hasExtra(KEY_PLAYLIST_ID)) playlistId=intent.getStringExtra(KEY_PLAYLIST_ID)
initExoPlayer(intent)
} else {
info("No new song information found for intent, intent's action: ${intent.action}")
}
if (intent.action == null) intent.action = ""
when (intent.action) {
ACTION_PLAY -> if (isPlaying()) pause() else play()
ACTION_CANCEL -> {
//TODO: implement a better and the correct way
for (client in clients) {
client.onStop()
}
stopSelf()
}
else -> showNotification()
}
return START_STICKY
}
and my activity:
playerService.clients.add(object : PlayerService.Client {
override fun onStop() {
finish()
}
})
And here is my custom notification:
private fun getCustomNotification(name: String, showMainActivity: Intent): Notification {
/*
some codes to prepare notificationLayout
*/
notificationLayout.setTextViewText(R.id.tv_name, name)
notificationLayout.setImageViewResource(R.id.btn_play, playDrawableID)
notificationLayout.setOnClickPendingIntent(R.id.btn_play, playPendingIntent)
notificationLayout.setOnClickPendingIntent(R.id.btn_cancel, cancelPendingIntent)
// Apply the layouts to the notification
return NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.logo_mouj)
.setCustomContentView(notificationLayout)
.setContentIntent(PendingIntent.getActivity(this, 0, showMainActivity, 0))
.setOngoing(true)
.build()
}