Home > Software engineering >  NotificationCompatBuilder instance for each Notification Channel?
NotificationCompatBuilder instance for each Notification Channel?

Time:08-24

I'm trying to create two different notifications with two different importance/priority levels. Do I have to create two different instances of a NotificationCompatBuilder:

NotificationCompat.Builder(context, "CHANNEL ID")
NotificationCompat.Builder(context, "CHANNEL ID 2")

since the builder accepts a specific Channel ID as we can see in the example above?

CodePudding user response:

Since Android 8.0 (API 26) all notifications must be assigned to a NotificationChannel. The NotificationChannel controls the priority of the notifications assigned to it with the importance parameter of the NotificationChannel.

Now, when creating the Notification via the Builder You will have the option to use the setPriority method. When it comes to Android 8.0 and later, calls to setPriority will have no effect on the Notification's importance. If You are targetting API < 26, then You will have to use setPriority no matter what the importance of the NotificationChannel of that Notification is.

Now, the answer to Your question is - it depends.

If You are targetting only API >= 26, then You want to use NotificationCompat.Builders with different channel IDs as only NotifcationChannels control the priority.

If You are targetting only API < 26, You will just want to use the setPriority method on the Builder and only one Builder would be enough in that case (but using two, with different channelIds would also be fine).

If You are targetting APIs that are both >= 26 and < 26 then You should use the approach as if You were targetting API >= 26 while additionally calling setPriority on the Builder (You can wrap the call to setPriority in the version check). This approach would require You to have two Builders with different channelIds.

  • Related