// 假设在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,可以自定义