I'm building my first app with Capacitor 5.4 and Svelte 3.49. The app is going to send notifications based on a remote API, it is fetching periodically an endpoint and based on the last API activity it calculates the date to schedule a LocalNotification and shows a countdown to the user. In foreground this logic works fine and with battery optimization off notifications are firing in time and with the exact frequency on Android emulator and my physical device.
In background and/or with off-screen notifications already scheduled work fine but if user doesn't open the app again there will never be a new scheduled notification. So my goal is to use Capacitor Background Runner with built-in interval which should make the API call and schedule the next notification. I managed to make it work in this way:
capacitor.config.json
"plugins": { ..."BackgroundRunner": {"label": "com.myproject.background.task","src": "background.js","event": "myCustomEvent","repeat": true,"interval": 5,"autoStart": true }, ... }
public/background.js
addEventListener('myCustomEvent', (resolve, reject, args) => { CapacitorNotifications.schedule([ { id: 100, title: 'myCustomEvent public', body: 'New scheduling available', scheduleAt: new Date(Date.now() + 10000), }, ]); resolve();});
The interval
isn't accurate but even a random periodical run is enough for my goal.As APIs here are limited and I cant just import my async calculations method, I need to rewrite it, fetch endpoint passing some variables and schedule a new notification using CapacitorNotifications.schedule
.
I really like capacitor, it makes it easy to develop apps but it's really hard to find examples of code implementation.
My questions are:
- Can I somehow dispatch an event from background.js to my App.svelte so inside App.svelte I can easly run my async fns to recalculate notification schedulings? (tried
dispatchEvent
without success) - Can I share some data between App and background.js? I need to pass a "username" variable to the endpoint so I need to access it inside background.js to perform the fetch. (I see there is CapacitorKV but I don't understand how to share use/share it.
Thank you!