通知栏消息多种提醒方式

有时候我们需要在白天让我们的通知消息跟随系统,但是夜晚需要静默提醒,不去打扰用户。就需要对Notification进行不同的设置。
下面上代码,兼容不同版本:

fun createNotification(messageBean: PushInlineMessageBean) {
    
    
        val isDefaultDuration = System.currentTimeMillis() < DateTools.getTodayHourTime(23) &&
                System.currentTimeMillis() > DateTools.getTodayHourTime(8)
        val channelId = if (isDefaultDuration) {
    
    
            DEFAULT_CHANNEL_ID
        } else {
    
    
            SILENT_CHANNEL_ID
        }

        val contentPendingIntent = PendingIntent.getActivity(
            App.instance,
            0,
            Intent.parseUri(messageBean.intent, Intent.URI_INTENT_SCHEME),
            PendingIntent.FLAG_UPDATE_CURRENT)

        val mBuilder = NotificationCompat.Builder(App.instance, channelId)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setWhen(System.currentTimeMillis())
            .setCategory(Notification.CATEGORY_MESSAGE)
            .setShowWhen(true)
            .setAutoCancel(true)
            .setContentTitle(messageBean.title)
            .setContentText(messageBean.content)
            .setContentIntent(contentPendingIntent)
            .setSmallIcon(R.drawable.icon)

        val mNotificationManager = App.instance.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
            val notificationChannel = NotificationChannel(channelId, CHANNEL_NAME, if (isDefaultDuration) {
    
    
                NotificationManager.IMPORTANCE_HIGH
            } else {
    
    
                NotificationManager.IMPORTANCE_LOW
            })
            mNotificationManager.createNotificationChannel(notificationChannel)
        } else {
    
    
            if (isDefaultDuration) {
    
    
                mBuilder.setDefaults(Notification.DEFAULT_ALL)
            } else {
    
    
                mBuilder.setVibrate(null)
                mBuilder.setSound(null)
                mBuilder.setLights(0, 0, 0)
            }
        }

        mNotificationManager.notify(random.nextInt() + 1, mBuilder.build())
    }

猜你喜欢

转载自blog.csdn.net/fwt336/article/details/118997619