kotlin

Android O 发送通知的方法(Kotlin)

2017-09-17  本文已影响0人  交响诗篇

谷歌的samples:https://github.com/googlesamples/android-NotificationChannels

昨晚把模拟器升级到Android O以后发现原来写的APP通知显示不出来了,前台服务也变成后台服务了,百度了一圈什么都没找到就去看了下Google的开发文档,从文档里得知NotificationCompat.Builder(context:Context)在Android O中将不再能显示出通知来,需要更换为Notification.Builder(context:Context,channelId:String)和给NotificationManager设置createNotificationChannel(channel:)才能正常显示。
注:channelId的值需要自己声明,根据samples得知有PRIMARY_CHANNEL和SECONDARY_CHANNEL两个等级,分别为: "default""second"

val PRIMARY_CHANNEL = "default"
val SECONDARY_CHANNEL = "second"

所以如果要在让APP在Android O以上显示出通知的写法应该是这样的:

val manager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel by lazy {
                NotificationChannel(PRIMARY_CHANNEL, "Primary Channel", NotificationManager.IMPORTANCE_DEFAULT)
            }
val notification =Notification.Builder(context.applicationContext, PRIMARY_CHANNEL)
.setContentTitle("标题")
……
.build()
manager.createNotificationChannel(channel)
//显示通知
manager.notify(0, notification)

这样就能在Android O中正常显示通知了。

上一篇下一篇

猜你喜欢

热点阅读