How to properly update notification channel android oreo

4.3k Views Asked by At

I'm trying to update a notification channel after I create it. Namely, I want to properly set the notification sound, but after I create it. I can't really figure out the proper way to do this.

What I tried was to delete the channel and re-create it but it doesn't seem to be working...

if (notificationManager != null) {
            notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL_ID);
            notificationManager.createNotificationChannel(channel);
            System.out.println("Created notification channel" + channel.getSound() + " " + channel.getImportance());
        }
2

There are 2 best solutions below

0
On

Once a notification channel is created, the user has ultimate control over its settings. As the developer, you can only change the channel's title and description. If you want to recreate the channel, you have to use a different id.

See: https://developer.android.com/training/notify-user/channels

0
On

It is correct like stated in the other answer that you can only alter the name and description of the channel once it has been created. However, as you point out in your code you can delete the channel and then create it again. But if you create the same channel once again but change something, for example the sound, it wont work. I'm assuming Android is preventing that change the same way it does if you try to create it when it already exists. So Android must have a way of keeping track of all the deleted channels (in other words, they are not completely deleted).

If you look at WhatsApp they allow you do change the sounds from within the app and if you investigate a little you'll find that they are indeed deleting and creating channels.

So what can you do? What you can do is that you can alter the ID of the new notification channel. Perhaps adding a big enough random element would prevent you from ever having the same ID twice. Or increment something and store that information within your app (prefs or db or something). If the "recreated" channel has a new ID Android will accept your "changes". Since you're not altering an existing channel, you're creating a completely new one. And if you keep the rest of the user-visible information intact (such as name, description etc) then the user will not notice this but only experience that the sound of that type of notification (channel) was altered from within the app.

Any downsides? Well, a superminor one is that Android will show in the App notification settings how many times a channel has been deleted (to alert the user of "spamming"). I don't think many users care about that. And you're also deviating from the design that Android wants (full user control of the channels) which perhaps might not be desirable.

So from how you describe your usecase I think it's fair to do it this way to accomplish what you want :)