How set Firebase notification ChannelID in Android O?

China☆狼群 提交于 2019-12-02 11:38:06

What I did in an app before was to initialize the Notification Channels as soon as the app starts. So I added an init function in my Application class, like so:

    @TargetApi(Build.VERSION_CODES.O)
    private void initNotificationChannels() {
        NotificationChannel publicChannel = new NotificationChannel(
                Constants.NOTIFICATION_CHANNEL_PUBLIC,
                Constants.NOTIFICATION_CHANNEL_PUBLIC,
                NotificationManager.IMPORTANCE_DEFAULT);
        publicChannel.setDescription(Constants.NOTIFICATION_CHANNEL_PUBLIC);

        NotificationChannel topicChannel = new NotificationChannel(
                Constants.NOTIFICATION_CHANNEL_TOPIC,
                Constants.NOTIFICATION_CHANNEL_TOPIC,
                NotificationManager.IMPORTANCE_DEFAULT);
        topicChannel.setDescription(Constants.NOTIFICATION_CHANNEL_TOPIC);

        NotificationChannel privateChannel = new NotificationChannel(
                Constants.NOTIFICATION_CHANNEL_PRIVATE,
                Constants.NOTIFICATION_CHANNEL_PRIVATE,
                NotificationManager.IMPORTANCE_HIGH);
        privateChannel.setDescription(Constants.NOTIFICATION_CHANNEL_PRIVATE);
        privateChannel.canShowBadge();

        List<NotificationChannel> notificationChannels = new ArrayList<>();
        notificationChannels.add(publicChannel);
        notificationChannels.add(topicChannel);
        notificationChannels.add(privateChannel);

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (mNotificationManager != null) {
            mNotificationManager.createNotificationChannels(notificationChannels);
        }
    }

Then in my FirebaseMessagingService, I made a function that gets the channelId when building notifications:

    private String getChannelId(String source) {
        if (!TextUtils.isEmpty(source)) {
            if (source.contains(Constants.TOPIC_PREFIX)) {
                return (TextUtils.equals((TOPIC_PREFIX + Constants.NOTIFICATION_CHANNEL_PUBLIC), source)) ?
                        Constants.NOTIFICATION_CHANNEL_PUBLIC : Constants.NOTIFICATION_CHANNEL_TOPIC;
            } else {
                return Constants.NOTIFICATION_CHANNEL_PRIVATE;
            }
        } else {
            return Constants.NOTIFICATION_CHANNEL_PUBLIC;
        }
    }

This caters to three types of notification that our app needs -- Public, Topic, and Private. You can specify the channels you need on your own.

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