繁体   English   中英

如何从 Android 中的前台服务发送通知

[英]How to send notifications from a Foreground Service in Android

我有一个前台服务,它在运行时显示正在进行的通知。

现在,它是一个流媒体应用程序,我希望在 stream 中断时(例如 inte.net 连接断开)通知用户。 我无法使用主应用程序,因为 stream 可以在其他应用程序处于活动状态时运行。 所以我需要从用于流式传输的前台服务向用户发送通知。 问题是,没有显示通知。

这是我目前正在使用的代码:

// 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() (将日志放在那里)但通知从未出现。

我改变了太多东西,以至于很难指定我尝试过的每一段代码。 但我尝试过的一些重要事情是改变频道/通知的优先级,并在相同/不同的频道中发送通知。 我还会在每次更改后卸载应用程序并重启手机,以确保应用通知设置。

到目前为止没有任何效果,这让我觉得这是不可能的。 我认为前台服务只允许显示一个通知(主要正在进行的通知)。

有人可以确认这一点或就如何使其发挥作用提出一些建议吗? 如果需要,我可以提供更多代码示例。

好吧,我感觉有点傻,但结果是设备上打开了“请勿打扰”。 这就是通知不可见的原因。 写这个作为答案,以防像我这样的人忘记关闭 DND 并找到这个 SO 问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM