Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Android, how to show notifications in lock screen?

I have already gone to:

  • Settings
  • Notifications & status bar
  • App notifications
  • [Application]
  • Enabled Lock screen notifications

However, I am not seeing a notification in the lock screen of my Android phone (Xiaomi Redmi 5A, Nougat). By the way, I am notifying locally. There's no push notification or GCM involved.

I tested the Gmail app, it is working fine. The Gmail notifications are showing in the lock screen.

Did I build the notification incorrectly? How should I build then?

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())
    }
}
like image 556
mownier Avatar asked Dec 19 '18 03:12

mownier


1 Answers

Try this...

You can use lockscreenVisibility property of NotificationChannel.ie.,

notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC

For example,

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())
}
like image 174
Silambarasan Poonguti Avatar answered Nov 08 '22 02:11

Silambarasan Poonguti