Correct way to create Notification Channels from Android O Api

sam_k picture sam_k · Sep 19, 2017 · Viewed 12.8k times · Source

The notification channels which introduced from Android O (API 26) version.I read about it from the following links:

Questions:

  1. If I have multiple numbers of notification then Is it a good idea to create notification channels when the application starts and keep it at ApplicationScope?

    public void addNotificationChannels(Context context) {
    
        List<NotificationChannel> channels = new ArrayList<>();
        channels.add("channel_1");
        channels.add("channel_2");
        .
        .
        channels.add("channel_7");
    
        NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannels(channels);
    
    }
    
  2. What will happen if I try to execute this line new Notification.Builder(getApplicationContext(), PRIMARY_CHANNEL) before adding channels to the notification manager

Answer

M66B picture M66B · Sep 21, 2017

What I do, is extending the application class (don't forget to update the app's manifest with the class name) and create the notifications channels once in the onCreate method. This guarantees the notification channels are always created when building a notification.

IMHO it is a waste of CPU cycles to (try to) create the notification channels for each notification over and over again.

As a side note: I always log the app version this way too, which is quite useful when somebody sends a logcat.