【问题标题】:How do you keep a notification from disappearing when the app is killed?当应用程序被杀死时,如何防止通知消失?
【发布时间】:2018-01-06 08:07:00
【问题描述】:

我正在尝试构建一个媒体播放器,但我不知道如何在用户终止应用程序时保持通知持续存在。音乐继续播放,但通知消失。如果我不杀死该应用程序,则通知将保留。奇怪的是,它确实出现在锁定屏幕上,但没有控制,但这是另一天的问题。

以下是一些相关代码:

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 在服务中只调用了两次。

private fun pauseMedia() {
    if (mp!!.isPlaying) {
        mp!!.pause()
        resumePosition = mp!!.currentPosition
        stopForeground(false)
    }
}

override fun onDestroy() {
    super.onDestroy()
    stopForeground(true)
}

感谢您提供的任何帮助!

【问题讨论】:

    标签: android kotlin android-mediaplayer


    【解决方案1】:

    尝试在 startForeground() 之前通知相同的通知。

    val notification = builder.build()
    NotificationManagerCompat.from(service).notify(246, notification)
    

    Refer this project。这也是一个音乐播放器,它使用这个方法来显示一个 MediaStyleNotification。

    【讨论】:

      猜你喜欢
      • 2020-03-01
      • 1970-01-01
      • 2017-04-12
      • 2016-02-10
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多