在锁定屏幕上显示通知

时间:2019-03-25 14:38:48

标签: android kotlin android-notifications

我正在显示PUBLIC通知。

我注意到某些设备没有在锁定屏幕上显示它们(仅在状态栏和通知抽屉中显示)。

使用Android 8的华为-在锁定屏幕上显示它们。

装有Android 7的魅族-不显示它们。但是会显示其他应用(谷歌,viber等)通知。

fun getNotification(context: Context, res: Resources): Notification {
        val channelId = "my.channel"
        val channelName = "My Channel - New Film"

        val notificationIntent = Intent(context, DiscoverActivity::class.java)
        notificationIntent.action = Intent.ACTION_MAIN
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER)

        val contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)

        // Channel
        generateChannel(context, channelId, channelName)

        return generateNotification(context, channelId, contentIntent, res)
    }

private fun generateNotification(context: Context, channelId: String, contentIntent: PendingIntent, title: String,
                                     text: String, res: Resources, silent: Boolean = false): Notification {
        val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val builder = NotificationCompat.Builder(context, channelId)
        builder.setContentIntent(contentIntent)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
            .setSound(alarmSound)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentTitle(title)
            .setContentText(text)
            .setWhen(System.currentTimeMillis())

        if (silent) {
            builder.priority = NotificationCompat.PRIORITY_LOW
        }

        return builder.build()
    }

    private fun generateChannel(context: Context, channelId: String, channelName: String, silent: Boolean = false) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val importance = if (silent) NotificationManager.IMPORTANCE_LOW else NotificationManager.IMPORTANCE_HIGH

            val chan = NotificationChannel(channelId, channelName, importance)
            chan.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
            chan.importance = importance
            if (!silent) {
                chan.lightColor = Color.GREEN
                chan.enableLights(true)
            }

            val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(chan)
        }
    }


// Launching

 val notification = notificationHelper.getNotification(this, resources)
 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 
notificationManager.notify(100, notification)

0 个答案:

没有答案
相关问题