[英]How do you keep a notification from disappearing when the app is killed?
I'm trying to build a media player, but I can't figure out how to keep the notification to persist when the user kills the app. 我正在尝试构建媒体播放器,但是当用户终止该应用程序时,我无法弄清楚如何保持通知继续存在。 The music continues to play, but the notification disappears.
音乐继续播放,但是通知消失。 If I don't kill the app, the notification stays.
如果我没有终止该应用程序,则通知将保留。 Oddly, it does appear on the lock screen, but there are no controls when it does, but that's a problem for another day.
奇怪的是,它确实出现在锁定屏幕上,但是什么时候都没有控件,但这又是一个问题。
Here's some relevant code: 这是一些相关的代码:
private fun buildNotification(action: Notification.Action) {
var style: Notification.MediaStyle = Notification.MediaStyle().setMediaSession(ms.sessionToken)
var intent = Intent(applicationContext, MediaPlayerService::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
var pIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
var builder: Notification.Builder = Notification.Builder(this)
.setSmallIcon(R.drawable.small_app_icon)
.setTicker(prefs.getString("EP_TITLE", ""))
.setContentTitle(prefs.getString("EP_TITLE", ""))
.setContentText("")
.setContentIntent(pIntent)
.setOngoing(true)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setStyle(style)
builder.addAction(generateAction(Icon.createWithResource(baseContext, R.drawable.back10s), "Back 10 Seconds", ACTION_REWIND))
builder.addAction(action)
builder.addAction(generateAction(Icon.createWithResource(baseContext, R.drawable.up30s), "Forward 30 Seconds", ACTION_FAST_FORWARD))
style.setShowActionsInCompactView(0,1,2)
startForeground(246, builder.build())
}
stopForeground is called only twice in the service. stopForeground在服务中仅被调用两次。
private fun pauseMedia() {
if (mp!!.isPlaying) {
mp!!.pause()
resumePosition = mp!!.currentPosition
stopForeground(false)
}
}
override fun onDestroy() {
super.onDestroy()
stopForeground(true)
}
Thanks for any help you can give! 谢谢你提供的所有帮助!
Try notifying the same notification before startForeground(). 尝试在startForeground()之前通知同一通知。
val notification = builder.build()
NotificationManagerCompat.from(service).notify(246, notification)
Refer this project . 请参考该项目 。 This is a music player too, it use this method to show a MediaStyleNotification.
这也是一个音乐播放器,它使用此方法显示MediaStyleNotification。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.