“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

An overview of

Notifications are one of the most frequently changed apis in Android. Android 4.1, 4.4, 5.0, 7.0, and 8.0 have all made significant changes to notifications. Notifications have stabilized in 8.0, and no major changes have been made to date.

It must be a very important API to take care of that much. Then follow me to reveal that the announcement is not a mystery at all.

Note: This article mainly focuses on application

Notice to use

Create simple notifications

We use NotificationCompat to create notifications, and with NotificationCompat we can work with all system versions without having to manually work with the version.

Creating notifications is a two-step process:

  • Create a channel
  • Create a notification

About the channel

Create a channel
Copy the code

Android 8.0 requires you to create channels to display notifications, so we have to add a way to create channels for android 8.0.

Creating channels doesn’t have to be done at the time of displaying notifications, the same channel can only be created once (or multiple times). We can create them when we’re about to display notifications, when the application starts, or in an activity. In short channel creation is very flexible

If the channel already exists and we still call the create channel method, then nothing will be done, so it’s safe, right

Here is the complete code to create our channel:

private val channelName = "Safe and sound."
private val channelId = "channelId"
fun createNotificationChannel(context: Context): NotificationChannel? {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val descriptionText = "Channel Description"
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(channelId, channelName, importance).apply {
                description = descriptionText
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            return channel
        return null
Copy the code
Channel importance setting

It is important to note that the priority of channels is different from that of notifications

val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(channelId, channelName, importance)
Copy the code

The third parameter of NotificationChannel is the importance of the channel. If the value of this parameter is set, the user’s display of the notification will be different, including the sound, vibration, and whether or not the notification will pop up. Here’s a look at the four parameters Settings (the four parameters are displayed differently in different channels on different phones) :

  • IMPORTANCE_HIGH Sends out the prompt when receiving the notification, and will float to prompt the user (Mi phone indicates emergency)
  • IMPORTANCE_DEFAULT When receiving a notification, it will not float.
  • IMPORTANCE_LOW Does not sound when receiving notifications, and small ICONS are displayed in the status bar.
  • IMPORTANCE_MIN doesn’t see notifications at all (so don’t use it at all), but it seems to be useful for disabling notifications.
Disable the notification method for a channel

We disabled notifications by creating channels as follows:

For example, when we first create the channel, the code looks like this:

val importance = NotificationManager.IMPORTANCE_HIGH
            val channel = NotificationChannel(channelId, channelName, importance)
Copy the code

This line of code creates a channel with an audible prompt, banner display (Google Docs calls this peeping mode 😄).

If the user does not want to receive notification from our channel through our internal app Settings at this time, we need the following code to do so:

val importance = NotificationManager.IMPORTANCE_MIN
            val channel = NotificationChannel(channelId, channelName, importance)
Copy the code

The difference from the previous code is that we changed IMPORTANCE_HIGH to IMPORTANCE_MIN, so our channel becomes a low level notification channel, and the notification is not displayed when received, so the user cannot see the notification at all, thus enabling the notification to be disabled.

It is also important to note that it is possible to code a high priority channel to a low priority channel, but it is not possible to set a low priority channel to a high priority channel.

About the notification

Create a notification

Notice that you’re all too familiar with, go straight to the code, remember to read the comments

Private val channelName = "context" private val channelId = "context" fun Context) { val notification = NotificationCompat.Builder(context, SetSmallIcon (r.drable.apple)// Set the type of notifications that the status bar displays .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drable.apple))// Set the icon style in the notification.setContentTitle(" official ")// Set the notification title.setContentText (" Safe ")// Set the notification body .setchannelId (channelId)// Set the notification channel, The channel id must be and when we create channels. The id of the corresponding setPriority (NotificationCompat. PRIORITY_DEFAULT). The build ()/notify priority/set NotificationManagerCompat.from(context).notify(13, notification) }Copy the code

Once again, make sure to create channels before showing notifications

Priority in notifications

Setting methods: NotificationCompat. Builder. SetPriority notice priority extremely easily confused with channel priority, must pay attention to distinguish between notice priority has the following kinds:

  • PRIORITY_DEFAULT = 0; Default priority
  • PRIORITY_LOW = -1; Low priority
  • PRIORITY_MIN = -2; Lowest priority
  • PRIORITY_HIGH = 1; High priority
  • PRIORITY_MAX = 2; Top priority

This parameter basically sorts our notifications, with the most important ones shown first. This helps us find the most important notifications to process first, which is useful, right?

Display effect

Display effect of the simulator:

Create an expanded notification

Create code

We can create NotificationCompat. Builder with the following call can show expansion inform:

SetStyle (NotificationCompat. BigTextStyle (.) bigText (\ "in this paper, by the public," zhuo in peace in peace \ "original author, forbidden copying \ n north scenery," + "freeze, you spend a look inside and outside the Great Wall, but a vast, up and down the river, Don't lose gushing, mountain dance silver snake, the original chi wax elephant, and heaven to try higher." + "must be sunny, look beautiful with snow wrapped in silver "))Copy the code

Notifications are expanded by default, and long-press notifications to switch back and forth between short text and long text

Display effect

Set the click event for notifications

The following code implements a clickable notification bar

fun showNotification(context: Context) { val intent = Intent(context,OnlyShowActivity::class.java).apply { flags=Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent=PendingIntent.getActivity(context,0,intent,0) val notification = NotificationCompat.Builder(context, ChannelId).setContentText(" Click notification to jump to a page ").setContentTitle(" Clickable notification ").setSmallIcon(R.drabable.apple) SetLargeIcon (BitmapFactory. DecodeResource (context) resources, R.d rawable. Apple)). SetAutoCancel (true) / / Settings click on the notification, Notifies the disappear automatically. SetContentIntent (pendingIntent). The build () NotificationManagerCompat. The from (context). Notify (+ + count, notification) }Copy the code

Set buttons for the notification bar

We can use addAction to set an action for a notification, and we can also specify a PendingIntent.

fun showBtnNotification(context: Context) { val intent = Intent(context, OnlyShowActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0) val notification = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.apple) .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.d. Rawable. Apple). AddAction (r.drawable. Person, "Liba ", pendingIntent). AddAction (R.drawable. Person," Liba ", pendingIntent). PendingIntent).addAction(R.drawable. Apple, "Wang Wi ", pendingIntent) .setAutoCancel(true) .build() NotificationManagerCompat.from(context).notify(++count, notification) }Copy the code

Setting the Progress bar

private val countdown = object : CountDownTimer(15 * 1000, 1000) { private val perdegree = 100 / 15 var count = 0 override fun onTick(millisUntilFinished: Long) {count++ showNotification(count * perdegree)} override fun onFinish() {showNotification(100) count = 0} {countdown.start()} private fun showNotification(progress: Int) { val builder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.apple) .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.d rawable. Person)). SetColor (Color. GREEN). SetContentTitle (" this is a progress of title ") NotificationManagerCompat. The from (context). Apply { Builder.setcontenttext (" $progress%") notify(count, builder.build())}} builder.setContentText(" $progress%")Copy the code


Set custom notifications

We can specify a layout with RemoteViews and set our custom layout code with setCustomContentView:

fun showNotification(context: Context){ val remoteViews = RemoteViews(context.packageName, R.layout.item_notification) val notification = NotificationCompat.Builder(context, ChannelId).setContentTitle(" the layout of this notification is custom ").setContentText(" peace ").setSmallIcon(R.drable.apple) .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.person)) .setCustomContentView(remoteViews) .build() NotificationManagerCompat.from(context).notify(count,notification) }Copy the code

A preview of our XML code:

Final effect:

Other points

  1. Starting from android8.1, an app can only play a notification tone once per second. If multiple notifications occur, only one notification tone can be played
  2. Create a notice several styles: NotificationCompat BigPictureStyle, NotificationCompat. BigTextStyle, NotificationCompat. DecoratedCustomViewStyle
  3. NotificationCompat. Builder. SetGroup method can create a set of notification
  4. NotificationManager. GetNotificationChannel () or NotificationManager. GetNotificationChannels () two methods to get the notification channel, You can obtain the importance level of whether the channel is enabled for sound and channel notification by obtaining the channel. We can prompt the user to open the Settings accordingly. The following code shows how to open the notification channel:
  Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
    intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
    intent.putExtra(Settings.EXTRA_CHANNEL_ID, myNotificationChannel.getId());

Copy the code
  1. Delete the method of channel deleteNotificationChannel ()
  2. We can call the channel NotificationChannel. SetShowBadge close the desktop icon dot (false) method. This is actually useful, for example, when you’re using notifications to show the download progress bar that obviously don’t need to show the dot, and most of the local notification classes don’t want to show the dot, so this is a good way to do it
  3. NotificationCompat. Builder. SetNumber method can set the number of red dots desktop ICONS
  4. Through NotificationCompat. DecoratedCustomViewStyle style can give the content area to create custom layout. The style is the notification that the display icon is on the left and our custom layout is on the right, but this feels useless.
  5. Custom layout notification can also be added to the internal view click jump event, the implementation method is as follows:
 val remoteViews = RemoteViews(context.packageName, R.layout.item_notification)
        val intent = Intent(context,OnlyShowActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(context,0,intent,0)
Copy the code

Welcome to follow my public account: “Anananzhuo”

Git: github.com/ananananzhu…