Android如何发送通知,用kotlin
时间: 2024-03-05 09:53:44 浏览: 16
在 Kotlin 中,您可以使用以下代码发送通知:
```kotlin
// 创建通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "Channel Name"
val descriptionText = "Channel Description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("channel_id", name, importance).apply {
description = descriptionText
}
// 注册通知渠道
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
// 创建通知
val notification = NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
// 发送通知
with(NotificationManagerCompat.from(this)) {
notify(0, notification)
}
```
上面的代码将创建一个名为 "Channel Name" 的通知渠道,并发送一条内容为 "Hello World!" 的通知。您需要根据实际的需求修改通知的内容和渠道的设置。