android 通知(android 8.0可用)
val CHANNEL_ID = "com.chao.channel.id"; val CHANNEL_NAME = "com.chao.channel.name"; val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager var builder = null //判断是否需要开启通道 if(shouldCreateNowPlayingChannel()){ //在这里开启通道 createNowPlayingChannel() } if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){ builder = Notification.Builder(this) }else{ builder = new Notification.Builder(this,Config.CHANNEL_ID) } notification = builder.build() mManager.notify(555, notification)
部分机型使用IMPORTANCE_LOW MIN NONE仍然发出提示音问题,修改channelId,可以解决
//判断是否需要创建通道 private fun shouldCreateNowPlayingChannel() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !nowPlayingChannelExists() //android8.0及以上才能调用 判断当前通道是否存在 //manager.getNotificationChannle(key) 如果通道已开启就能获取到 否则获取为null @RequiresApi(Build.VERSION_CODES.O) private fun nowPlayingChannelExists() = manager.getNotificationChannel(CHANNEL_NAME) != null @RequiresApi(Build.VERSION_CODES.O) private fun createNowPlayingChannel() { /** * Oreo不用Priority了,用importance * IMPORTANCE_NONE 关闭通知 * IMPORTANCE_MIN 开启通知,不会弹出,但没有提示音,状态栏中无显示 * IMPORTANCE_LOW 开启通知,不会弹出,不发出提示音,状态栏中显示 * IMPORTANCE_DEFAULT 开启通知,不会弹出,发出提示音,状态栏中显示 * IMPORTANCE_HIGH 开启通知,会弹出,发出提示音,状态栏中显示 */ val notificationChannel = NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH ) .apply { description = "test" } manager.createNotificationChannel(notificationChannel) }

浙公网安备 33010602011771号