Android:创建通知渠道并发送文章更新通知(通知 Notification)
先不急着背概念。下面这个例子只做一件事:通知栏显示“有新文章”,点击进详情。跑通之后,再回头看「创建通知渠道并发送文章更新通知」会轻松很多。
它解决什么问题
通知栏显示“有新文章”,点击进详情。重点不是记住代码,而是看清输入、处理和输出之间的对应关系。
示例代码
顶部注释不是装饰,标的是每个关键函数/类为什么存在。读代码时可以从那里入手。
// 这段代码要解决的问题:通知栏显示“有新文章”,点击进详情
// 关键类/函数:
// - NotificationChannel:创建通知渠道
// - NotificationCompat.Builder:构建通知内容
// - notify():发送通知
val channelId = "posts"
val manager = getSystemService(NotificationManager::class.java)
val channel = NotificationChannel(
channelId, "文章更新", NotificationManager.IMPORTANCE_DEFAULT
)
manager.createNotificationChannel(channel)
val notification = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("有新文章")
.setContentText("点击查看最新内容")
.setContentIntent(pendingIntent)
.build()
manager.notify(1, notification)代码为什么这样写
NotificationChannel:创建通知渠道NotificationCompat.Builder:构建通知内容notify():发送通知
结果不对时先看这里
过早抽象:示例还没看懂就套设计模式,最后维护成本反而更高。
练习
- 先不看代码,写出你对「创建通知渠道并发送文章更新通知」执行过程的预测,再运行对照。
- 改掉
NotificationChannel的一行关键实现,观察报错信息,再恢复它。
别急着收藏。关掉页面,自己重写一遍,能独立跑通才算真的会。
评论 0
友善交流,让讨论变得更有价值。