MST

星途 面试题库

面试题:Kotlin中Android通知基础设置

在Kotlin中,如何创建一个基础的Android通知,包含设置通知的标题、内容以及小图标?请写出关键代码片段。
32.5万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
// 假设在AndroidX环境下,导入必要的包
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat

// 创建通知渠道(Android 8.0及以上需要)
val CHANNEL_ID = "my_channel_id"
val channelName = "My Channel"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val channel = NotificationChannel(CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_DEFAULT)
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(channel)
}

// 创建通知
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
   .setSmallIcon(R.drawable.ic_notification) // 设置小图标,替换为你的图标资源
   .setContentTitle("通知标题")
   .setContentText("通知内容")
   .build()

// 发送通知
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1, notification) // 1是通知的ID,可以自定义