[Android] The latest version of Android 13 uses Notification, basic use and advanced use of Notification

1. Use Notification

1. Create a notification

1.1 Register a channel

In Android13, new changes have occurred in the use of version notifications.

1.1.1 NotificationManager native class

First we need to create oneNotificationManager for managing notifications. NotificationManager Only supported on devices with API level 11 (Android 3.0) and above, so newer notification features cannot be used on older Android versions .

//创建notificationManager对通知进行管理
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
`1.1.2 NotificationManagerCompat compatible class

NotificationManagerCompat is a notification managementcompatible class provided in the Android Support Library (now the AndroidX library). It is used to support notification management on devices of various API levels and provides a consistent notification management interface without the need for manual version adaptation.

  NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

Just choose any one of these two methods.

Next, you need to register a channel. The notification channel is a mechanism for classifying and managing notifications.

// 在 MainActivity 或其他合适的地方创建通知渠道
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
    String channelId = "001";   //通知渠道的标识符
    CharSequence channelName = "QQ";    //通知渠道的位置
    String channelDescription = "来自QQ好友的消息";    //通知渠道的描述

    //设置通知渠道的级别
    int importance = NotificationManager.IMPORTANCE_DEFAULT;

    //创建通知渠道
    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
    notificationChannel.setDescription(channelDescription);//可以省略
   

    //在系统中注册消息
    notificationManager.createNotificationChannel(notificationChannel);

}

By if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) conditional judgment, ensure that the Android version running on the current device is 8.0 or higher. Only in this case will the notification channel be created.

Then, three variables are defined and a channel level is set for setting the properties of the notification channel:

parameter illustrate
channelId The ID of the notification channel, which is not visible to the user and is needed when instantiatingNotification.
channelName The name of the notification channel. This is convenient for users to manage notifications. It is visible to users.
channelDescription Description of the notification channel. Used to display detailed descriptions of notification channels to users in the system settings interface and notification management.
importance Channel Priority

There are three priority levels for channels:

  1. IMPORTANCE_DEFAULT: (default level)
  2. IMPORTANCE_HIGH:(high)
  3. IMPORTANCE_LOW:(Low)
  4. IMPORTANCE_MAX: The most important notification, the system will immediately display the message on the screen

image-20230802205341946

Next, create a channel throughNotificationChannel. The three parameters of the construction method are: Id, name, and importance.

Set the description message of the channel throughsetDescription() method

Finally, just register the message in the system:

notificationManager.createNotificationChannel(notificationChannel);

1.2. Expand knowledge CharSequence

The advantage of usingCharSequence type is that it is a general interface that can contain different types of character sequences, including immutable stringsString and Mutable stringsStringBuilder, StringBuffer, etc. In this way, when we define notification channels, we can use variables of type CharSequence to allow different types of character sequences to be passed.

1.3 Create notifications

Note that Android 8 and above require permissions

//申请通知权限
if (ContextCompat.checkSelfPermission(MainActivity.this,
                                      Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
    
    
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{
    
    Manifest.permission.POST_NOTIFICATIONS}, 1);
}

You also need to register in AndroidManifest:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />

Next, create the notification:

//创建通知
Notification notification = new NotificationCompat.Builder(MainActivity.this, "001")
    .setContentTitle("QQ消息")    //消息的标题
    .setContentText("你好,我是张三")  //消息的内容
    .setWhen(System.currentTimeMillis())    //指定通知被创建的时间
    .setSmallIcon(R.drawable.notify)    //通知的小图标
    .setLargeIcon(BitmapFactory.decodeResource
                  (getResources(), R.drawable.notify)) //通知的大图标
    .build();

//显示一个通知
notificationManager.notify(1, notification);

In the setLargeIcon() method, you need to pass a Bitmap object as the content of the large icon. BitmapFactory.decodeResource(getResources(), R.drawable.notify) is used here to convert the R.drawable.notify resource into a Bitmap object and set it as a large icon for the notification.

image-20230802184739177

1.4 Set click event for message

//点击通知后跳转页面
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

UsePendingIntent, which has four parameters:

image-20230802185336157

  1. The second parameter is generally not used, and is usually passed in 0.
  2. The third parameter is the Intent object
  3. The fourth parameter is a flag used to determine the intended behavior

There are four values ​​available, usuallyFLAG_IMMUTABLE

  • PendingIntent.FLAG_IMMUTABLE: This is a flag introduced in Android 12 (API level 31) and higher. The created PendingIntent object will become immutable. ImmutablePendingIntent cannot modify its content, flags, or other attributes after creation, improving security and performance .

  • PendingIntent.FLAG_UPDATE_CURRENT: is used to specify that if the created PendingIntent already exists, then use the existing PendingIntent , and update the Intent content with the newly passed in Intent. If it does not exist, create a new one PendingIntent. This flag is usually used in scenarios where the same PendingIntent is created multiple times, ensuring that there is only one PendingIntent instance, and among them. a>Intent content is kept up to date.

  • PendingIntent.FLAG_CANCEL_CURRENT: If the created PendingIntent already exists, then cancel the existing PendingIntent. Then create a newPendingIntent. That is, cancel the existing PendingIntent first, and then create a new one.

  • PendingIntent.FLAG_NO_CREATE: If the created PendingIntent already exists, a new PendingIntent will not be created, but Returns the existingPendingIntent. If it does not exist, return null. This flag is usually used to query whether a specific PendingIntent already exists, without actually creating a new instance .

Finally use when creating the notification add:

.setContentIntent(pi)   //点击后的跳转事件

Then click on this notification to jump.

Through this animation, we find that the notification still does not disappear after clicking on it. Why is this?

There are two solutions:

  1. One is to add another **setAutoCancel()** method inNotificationCompat.Builder

image-20230802192621642

  1. The other is to explicitly call the **cancel()** method inNotificationManager.

image-20230802193106168

This 1 is the id we set for this notification when we created it.

image-20230802193052710

2. Advanced usage of notifications

Android 13 requires registration in the channel

2.1 Set vibration

//注册震动
long[] vibrationPattern = {
    
    100, 200, 300, 400}; // 设置震动模式,参数为一个 long 类型数组,表示震动的时长和间隔
// 配置通知出现时的震动(如果 Android 设备支持的话)
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(vibrationPattern);

notificationChannel.setVibrationPattern(vibrationPattern); This code does not need to be set in the channel. You only need to use notificationChannel.enableVibration(true); to register.

Then in the notificationNotificationCompat.Builder:

.setVibrate(new long[]{
    
    100, 200, 300, 400})

Pay attention to setting permissions;

<uses-permission android:name="android.permission.VIBRATE"/>

2.2 Set the flashing light

// 设置通知渠道的闪灯效果
notificationChannel.enableLights(true); // 允许通知闪灯

Then in the notificationNotificationCompat.Builder:

.setLights(Color.RED,1000,2000)

The first parameter is the color, the second is the duration of the light, and the third is the duration of the dark

2.3 Set sound

.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Big_Easy.ogg")))

2.4 Create rich text notification content

.setStyle(new NotificationCompat.BigTextStyle().bigText("ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"))

2.5 Show large image

.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(BitmapFactory.decodeResource(getResources(),R.drawable.notify)))

Guess you like

Origin blog.csdn.net/m0_72983118/article/details/132071778