更新时间:2023-02-26 21:01:19
从Android 8.0(API级别26)开始,通知需要一个通知渠道.您需要为通知创建并附加一个通知渠道.
Starting in Android 8.0 (API level 26), notifications require a notification channel. You need to create and attach a notification channel for your notification.
private fun initChannel(channelId: String, channelName: String) {
if (Build.VERSION.SDK_INT < 26) {
return
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
然后
private fun startTripNotification() {
initChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME)
val pendingIntent = PendingIntent.getActivity(activity, 0, Intent(), 0)
val notification = NotificationCompat.Builder(activity,NOTIFICATION_CHANNEL_ID)
.setContentTitle("test notification title")
.setContentText("test notification text")
.setSmallIcon(R.mipmap.ic_main_icon_round)
.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.mipmap.ic_launcher))
notification.setContentIntent(pendingIntent)
val notificationManager = activity?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notification.build())
}
您可以在此处