android - 通知未在android中发送
问题描述
我在这个问题上卡了很久,不知道哪里出了问题。我正在使用广播接收器发送预定的通知。我已经验证了广播接收器的 onReceive() 方法正在相应地被触发,它只是没有被发送的通知。
class AlertReceiver() : BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context?, intent: Intent?){
val notificationChannel =
NotificationChannel("My Channel", "My Channel", NotificationManager.IMPORTANCE_DEFAULT).apply {
description = "Sends Alarms"
}
val builder = NotificationCompat.Builder(context!!, "My Channel")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Alarm is ringing")
.setContentText("Alarm is working")
with(NotificationManagerCompat.from(context)){
// Verification that onReceive is firing
Toast.makeText(context, "Alarm is supposed to ring", Toast.LENGTH_SHORT).show()
notify(1, builder.build())
}
}
}
我还在另一个练习应用程序中使用了完全相同的代码,并且得到了预期的行为,所以我认为它与 build.gradle 文件或 android 清单有关。这个问题已经困扰我好几天了,所以我将不胜感激任何解决方案
解决方案
除了创建NotificationChannel
对象之外,还要在应用程序系统设置中注册它createNotificationChannel
with(NotificationManagerCompat.from(context)){
createNotificationChannel(notificationChannel) // in here!
// Verification that onReceive is firing
Toast.makeText(context, "Alarm is supposed to ring", Toast.LENGTH_SHORT).show()
notify(1, builder.build())
}
之后尝试发布通知
PS。对建设者也有一些小的改进
NotificationCompat.Builder(context!!, notificationChannel.getId())
推荐阅读
- shell - Shell 命令在 Jenkins 管道中不起作用
- python-sphinx - 脚注作为与 reStructuredText 和 Sphinx 的上标链接
- nginx - Datadog 与 NGiNX 的集成
- java - 将现有字符串与 Environment.getExternalStorageDirectory().getPath() 进行比较的问题
- javascript - 为什么动画没有按预期工作?
- python - 将带有值的numpy数组转换为每行中每个观察值的频率数组
- angular - Angular 5 router.navigate 让我远离 Angular 应用程序
- javascript - 将课程添加到活动幻灯片
- c# - 使用 OCR 精确复制文本
- r - 无法运行语句:查询期间丢失与 MySQL 服务器的连接