【发布时间】:2021-08-11 14:48:56
【问题描述】:
我有一个前台服务,它在运行时显示持续通知。
现在,它是一个流媒体应用程序,我希望在流媒体中断(例如互联网连接中断)时通知用户。我无法使用主应用程序,因为当其他应用程序处于活动状态时,流可能会继续。因此,我需要从用于流式传输的前台服务向用户发送通知。问题是,通知没有显示出来。
这是我目前使用的代码:
// registering notification channels
private fun createNotificationChannels() {
val serviceChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID_SERVICE,
NOTIFICATION_CHANNEL_NAME_SERVICE,
NotificationManager.IMPORTANCE_DEFAULT
)
val appChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID_APP,
NOTIFICATION_CHANNEL_NAME_APP,
NotificationManager.IMPORTANCE_HIGH
).apply {
enableVibration(true)
}
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannels(mutableListOf(serviceChannel, appChannel))
}
// starting the service with a required notification
startForeground(
nextInt(100000),
NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_SERVICE)
.setSmallIcon(R.drawable.recording_notification)
.setContentText("Stream is in progress...")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build(),
ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
)
// letting the user know that stream crashed
private fun sendDisconnectNotification() {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_APP)
.setSmallIcon(R.drawable.disconnected_notification)
.setContentTitle("The stream stopped unexpectedly!")
.setContentText("Please check your internet connection.")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.notify(nextInt(100000), builder.build())
}
我知道正在调用 sendDisconnectNotification()(将日志放在那里),但通知从未出现。
我更改了很多东西,以至于很难指定我尝试过的每一段代码。但我尝试的一些重要事情是更改频道/通知的优先级并在相同/不同的频道中发送通知。我还会在每次更改后卸载该应用并重新启动手机,以确保应用通知设置。
到目前为止,没有任何效果,这让我觉得这是不可能的。我认为前台服务只允许显示一个通知(主要正在进行的通知)。
有人可以确认这一点或就如何使其发挥作用提供一些建议吗? 如果需要,我可以提供更多代码示例。
【问题讨论】:
标签: android kotlin notifications foreground-service