首页 > 解决方案 > 在 Android 中,如何在锁定屏幕中显示通知?

问题描述

我已经去了:

但是,我在我的 Android 手机(小米红米 5A、牛轧糖)的锁定屏幕中没有看到通知。顺便说一句,我在本地通知。不涉及推送通知或 GCM。

我测试了 Gmail 应用程序,它运行良好。Gmail 通知显示在锁定屏幕中。

我是否错误地构建了通知?那我应该怎么建?

private fun showNotificationWith(message: String) {
    val channelId = "com.example.notif.channelId"
    val channelName = "App status"
    val contentTitle = "Title"
    val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_small_exclamation)
            .setContentTitle(contentTitle)
            .setContentText(message)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        val importance = NotificationManager.IMPORTANCE_HIGH
        val notificationChannel = NotificationChannel(channelId, channelName, importance)
        notificationBuilder.setChannelId(channelName)
        notificationManager.createNotificationChannel(notificationChannel)
        notificationManager.notify(message.hashCode(), notificationBuilder.build())

    } else {
        notificationManager.notify(message.hashCode(), notificationBuilder.build())
    }
}

标签: androidkotlinnotifications

解决方案


尝试这个...

您可以使用lockscreenVisibilityNotificationChannel.ie 的属性,

notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

例如,

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    val importance = NotificationManager.IMPORTANCE_HIGH
    val notificationChannel = NotificationChannel(channelId, channelName, importance)
    notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

    notificationBuilder.setChannelId(channelName)
    notificationManager.createNotificationChannel(notificationChannel)
    notificationManager.notify(message.hashCode(), 
    notificationBuilder.build())
} else {
    notificationManager.notify(message.hashCode(), notificationBuilder.build())
}

推荐阅读