This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

preface

Message notifications are an essential part of application development. For example, when an IM application receives a message, the notification bar must be lifted to inform the user of the brief information to obtain the brief information. Or an e-commerce app or news app will need to use Notification when promotions and important inquiries are pushed to users. Notification is an important part of an application’s ability to evoke and use it. Good notifications help to increase application usage and DAU.

The use of the Notification interface has also changed significantly over a number of iterations of system releases. Previously, the Notification interface was in the Support package in older versions, and later, after compatibility, NotificationCompat was adopted. Since many contents of the new version of notification serve the higher version of Android system, some notification types cannot achieve the corresponding effect in some lower version of Android system, and some notification styles cannot reach the expected effect due to the system customization by domestic mobile phone manufacturers. These problems do exist and the fragmentation of the Android ecosystem is inevitable. Developers can only make efforts to ensure that the features are perfect.

Create a notification

Notification adopts the Design mode of Builder. The parameter configuration of Notification bar is completed in Builder, and then the Notification instance is created by Builder. Finally, NotificationManager is used to display Notification messages. The notification simply uses the following code:

mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(NotificationActivity.this."001")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setTicker("new message")
                .setContentTitle("My notification")
                .setContentText("Hello World!");

mNotificationManager.notify(1, mBuilder.build());

Copy the code

However, the above code does not enable the notification bar effectively on the mobile phone with the advanced OS. The error log is as follows:

There are more ways to notify on older systemschannelIdFor this concept to take effect, developers need to register the channelId channel for notifications themselves and send notifications to the channel.

The modified code looks like this, adding the NotificationChannel registration operation:

mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

//ChannelId is "001",ChannelName is "my_channel"
NotificationChannel channel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    channel = new NotificationChannel("001"."my_channel", NotificationManager.IMPORTANCE_DEFAULT);
    channel.enableLights(true); // Whether to display a red dot in the upper right corner of the desktop icon
    channel.setLightColor(Color.GREEN); // Small red dot color
    channel.setShowBadge(true); // Whether to display notifications for this channel on desktop ICONS
    mNotificationManager.createNotificationChannel(channel);
}

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(NotificationActivity.this."001")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setTicker("new message")
                .setContentTitle("My notification")
                .setContentText("Hello World!");
mNotificationManager.notify(1, mBuilder.build());
Copy the code

Notification Builder parameter

Below is NotificationCompat. Builder parameter method, which are frequently used as setSmallIcon, setContentTitle, setContentText belongs to the field will not exist system compatibility problems. SetLights, on the other hand, may depend on the hardware of the system itself.

Method Introduction
setSmallIcon Set notification mini icon (mandatory)
setLargeIcon Set the notification icon
setContentTitle Set notification title (mandatory)
setContentText Set notification content (mandatory)
setDefaults Message alert mode (sound/vibrate/alert light…)
setSound Set a customized message reminding tone
setVibrate Set vibration frequency
setLights Set the prompt light display
setOngoing Set whether the notification can be clear in the notification list
setOnlyAlertOnce Notification no longer reminds if it already exists
setAutoCancel Whether the message is still displayed in the notification bar after it is clicked
setProgress Set the progress and display the progress style on the notification bar
setContent Used to set custom notifications
setContentIntent Set notification click jump content

Create an expanded layout notification

The main reason for creating an expansion notification is to be able to show more information content. The generic notification style is limited in how much content can be displayed, so expandable displays are used to provide more information.

BigPictureStyle

BigPictureStyle supports displaying notifications for large images. Here are a few parameters that can be set

  • setBigContentTitle
  • setSummaryText
  • bigLargeIcon
  • bigPicture
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle("Title");
bigPictureStyle.setSummaryText("SummaryText");
Bitmap bigPicture = BitmapFactory.decodeResource(getResources(),R.drawable.android);
bigPictureStyle.bigPicture(bigPicture);
builder.setStyle(bigPictureStyle);
Copy the code

BigTextStyle

Display text notification, you can display more text content. It feels similar to inboxStyle.

  • setBigContentTitle
  • setSummaryText
  • bigText
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle("Title");
bigTextStyle.bigText("BigText\nBigText\nBigText\nBigText\nBigText");
bigTextStyle.setSummaryText("SummaryText");
builder.setStyle(bigTextStyle);
Copy the code

MessagingStyle

Message notification, which can be quickly replied to message notification. It seems to be available on Android N or higher. The current test machine is a low version, and there is no quick reply operation item. addMessage setConversationTitle

NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle("UserName");
messagingStyle.addMessage("message",System.currentTimeMillis(),"JulyYu");
messagingStyle.setConversationTitle("Messgae Title");
builder.setStyle(messagingStyle);
Copy the code

InboxStyle

Can display multi-line text notification, through addline and can add a new line of text content.

  • setBigContentTitle
  • setSummaryText
  • addLine
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String[] events = new String[]{"1","2","3","4"};
inboxStyle.setBigContentTitle("Event tracker details:");
inboxStyle.setSummaryText("SummaryText");
for (int i=0; i < events.length; i++) {
    inboxStyle.addLine(events[i]);
}
builder.setStyle(inboxStyle);
Copy the code

MediaStyle

PS: Is no longer available in higher versions of NotificationCompat

Multimedia play notification, fast multimedia control operation. You can customize the content of the action control that you want to display.

  • setShowActionsInCompactView
  • setMediaSession
  • setShowCancelButton
  • setCancelButtonIntent

Compatibility issues

Because the notification API is constantly evolving, it is still used on older systems. Therefore, it is recommended that developers use NotificationCompat to create notifications, so that developers do not need to do version compatibility on their own. Of course some of the new features and apis are only available in older versions and will not work on older devices.

Android4.1

  1. Supports the expanded notification mode
  2. Support to add button operations on notifications
  3. Allows users to turn off notifications in Settings

Android4.4

  1. Support for adding notification listener services

Android5.0

  1. Supports screen lock notification
  2. Added notification priority concept

Android7.0

  1. Added the application mode of SMS notification
  2. Users can reply to notifications directly in the notification bar

Android8.0

  1. Notice use must have specific notification channel registration and linkage
  2. Notification priority Settings have been changedNotificationChannel.setImportance()

reference

  • API Guides