32
loading...
This website collects cookies to deliver better user experience
NotificationManager
from NotificationManagerCompat
. That’s the interface used for dealing with notifications on Android. Then we create a NotificationChannel
that takes the channel’s id, name and importance as arguments. It’s advised to use NotificationManager.IMPORTANCE_HIGH
for increasing the chances of the notification appearing as a heads up notification. We also change the lockscreenVisibility
to Notification.VISIBILITY_PUBLIC
to tell Android that the notification can be shown on the lock screen. Finally we call notificationManager.createNotificationChannel
to register the channel.createNotificationChannel
multiple times with the same channel, Android will ignore it if there’s an existing channel with the same id.Application.onCreate
is called.PendingIntent
, that’s the intent that will be called when the notification is clicked, here we’ll simply start an activity. Then we call NotificationCompat.Builder
to define how the notification will look like. The CHANNEL_ID
parameter has to have the same id we used earlier to create the channel. If you want to learn how to customize you notification you can take a look at the Android Documentation.notificationManager
to show the notification. The notification id can be any number, it’s used only if you need to interact with the notification later.showWhenLockedAndTurnScreenOn
after onCreate
to define that the activity can appear on the lock screen and that the screen should be turned on when it appears. I added the method to the activity but you can easily add that as an extension to Activity in case you use it in other places.launchMode
and showOnLockScreen
.createNotification
method we defined earlier. We need to create another PendingIntent
that’ll start the activity that’ll be shown on the lock screen. We then pass that intent to setFullScreenIntent
. It’s also important to add a category such as ALARM or CALL for increasing the chances of it appearing on the lock screen.Here’s the end result
notificationManager.cancel(id)
when the lock screen activity is destroyed.