cordovaionic-frameworkcordova-pluginscapacitorcapacitor-plugin

Update Notification in Capacitor's Local Notification Plugin


Is there any alternative capacitor community plugin with a function to update the emitted notification.

There was a Cordova plugin cordova-plugin-local-notifications which has the ability to update the emitted notification

cordova.plugins.notification.local.update({
    id: 15,
    text: [{ person: 'Irish', message: 'Bye bye' }]
});

Capacitor's Local notification plugin @capacitor/local-notifications doesn't have this support.

Wondering is any plugin available like this in capacitor.


Solution

  • Android will update the notification when the same notification id is passed.

    we can use setOnlyAlertOnce flag if we would only like the sound, vibrate and ticker to be played if the notification is not already showing.

    https://developer.android.com/develop/ui/views/notifications/build-notification#Updating

    While I'm going through the Capacitor's Local Notification Plugin's Native Android code noticed there was method dismissVisibleNotification(id) which is canceling the existing notification.

    Hence the updated notification looks like a new notification.

    @Nullable
        public JSONArray schedule(PluginCall call, List<LocalNotification> localNotifications) {
            JSONArray ids = new JSONArray();
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    
            boolean notificationsEnabled = notificationManager.areNotificationsEnabled();
            if (!notificationsEnabled) {
                if (call != null) {
                    call.reject("Notifications not enabled on this device");
                }
                return null;
            }
            for (LocalNotification localNotification : localNotifications) {
                Integer id = localNotification.getId();
                if (localNotification.getId() == null) {
                    if (call != null) {
                        call.reject("LocalNotification missing identifier");
                    }
                    return null;
                }
                dismissVisibleNotification(id);
                cancelTimerForNotification(id);
                buildNotification(notificationManager, localNotification, call);
                ids.put(id);
            }
            return ids;
        }
    
    
    private void dismissVisibleNotification(int notificationId) {
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this.context);
        notificationManager.cancel(notificationId);
    }