Correct way to create Notification Channels from Android O Api

﹥>﹥吖頭↗ 提交于 2019-12-05 03:38:31

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.

  1. Ideally, you should create channel while posting notification to it. It is safe to call createNotificationChannel with same id used previously, it will not be recreated.
  2. Your application won't post this notification. System might show warning toast that your app is not allowed to post this notification.

A) At the same time you create the notification:

As the documentation says:

Creating an existing notification channel with its original values performs no operation, so it's safe to call this code when starting an app.

So you can safety create the notification channel at the same time you create the notification itself, there is no need to check if the channel is already created.

B) Inside Application or any Activity/Fragment.

Note: In case you are using raw FCM, is interesting to create the channel before the SDK publishes the notification for you because according the push payload param android_channel_id, you can associate that push to a specific channel already created in your app.

Fcm payloads: https://firebase.google.com/docs/cloud-messaging/http-server-ref

I think there are two sensible ways:
1. Create all channels in Application subclass,
2. Create all channels in your main Activity, which first starts with the app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!