supabase_realtime_push 0.1.0
supabase_realtime_push: ^0.1.0 copied to clipboard
Push notifications on Android without Firebase: a native service holds one Supabase Realtime connection and shows the notifications your database lists.
Push notifications for Flutter + Supabase apps on Android, without Firebase Cloud Messaging (FCM).
One Supabase Realtime connection, an empty signal, and a notification shade
that always matches your database.
Works with Supabase Cloud and with self-hosted Supabase.
No FCM project and no google-services.json.
Status: first release; the API may still change before 1.0. The design is in doc/contract.md.
What it does #
A push notification is the message that pops up on a phone, like "Your order has shipped", even when the app is closed. On Android, apps almost always get them through Firebase, a Google service that needs Google's apps on the phone.
This library does the same job without Google. It is for Android apps made with Flutter (a toolkit for building apps) that use Supabase (a ready-made database and server). A small helper on the phone keeps one connection open to the server, without starting the whole app. It works like a doorbell: when something changes, the server only rings the bell. The phone then asks "what should I show now?" and makes its notification list match the answer. With the screen on that takes a second or two; with the screen off the phone mostly sleeps, so a notification can take up to about five minutes, or about fifteen when the phone has been still for a long time. If the connection drops, in an elevator or on weak Wi-Fi, the phone asks again once it is back, so nothing is lost. A message read on another phone disappears from this one.
Who it is for #
It is for company phones without Google, fleets that install the app from a
file instead of the Play Store, and teams that run their own Supabase server.
It is not for iPhones, which do not let an app keep a connection open in the
background. If your app is on the Play Store and every user has Google, use
Firebase: it shares one connection among all the apps on a phone. The cost is
real: each phone holds a connection to your server while its screen is on.
Android also shows a small "connected" notification unless the app is exempt
from battery optimization. Ask for the exemption once when the user turns
notifications on (one tap, or none on a managed fleet) and it goes away. If
you cannot ask, start(foregroundService: false) never shows it, and
notifications then arrive more slowly with the app closed (see
Battery).
Contents #
- How it works
- Platform support
- Setup: database · Flutter · register and start · sign out · send · taps
- Your own data instead of the inbox
- Reply from the notification
- Mark as read from the notification
- Channels and pictures
- The screen the user is looking at
- Battery and the "connected" notification
- Security
- Limits
- Feedback and contributing
How it works #
- The app registers the device with your project: a random topic and secret, one pair per device. The database keeps only the secret's hash.
- A native Android service keeps one WebSocket to Realtime, listening on that device's topic. It runs without the Flutter engine, so it uses a few MB of memory.
- When something changes, the database sends an empty
changedsignal to the topic. No content ever travels over the socket. - The service asks a SQL function for the snapshot (every notification the device should show right now) and makes the shade match it: new ones alert, changed ones update quietly, gone ones disappear.
Platform support #
| Android | iOS | Web | Desktop |
|---|---|---|---|
| ✅ 7.0+ | ❌ iOS does not allow a background socket; use APNs | ❌ | ❌ |
On other platforms every call is a no-op, except device(), which throws, so
you can keep one code path and check SupabaseRealtimePush.isSupported.
Setup #
1. Database #
Add supabase/realtime_push.sql, at the tag of the package version you
depend on, as a migration with the
Supabase CLI, then push it:
curl -o "supabase/migrations/$(date +%Y%m%d%H%M%S)_realtime_push.sql" \
https://raw.githubusercontent.com/Franklyn-R-Silva/supabase_realtime_push/v0.1.0/supabase/realtime_push.sql
supabase db push
Without the CLI, run that file in the SQL editor.
To upgrade, when the CHANGELOG says the SQL changed, add a new migration with
the new version's file the same way; do not edit the old one. The script is
re-runnable and keeps your own realtime_push_snapshot_for,
realtime_push_reply_for and realtime_push_read_for.
It creates, in public:
| Object | Called by | Does |
|---|---|---|
realtime_push_register(p_topic, p_secret, p_platform) |
the app, signed in | Links this device to auth.uid() |
realtime_push_unregister(p_topic) |
the app, signed in | Unlinks it (on sign-out) |
realtime_push_snapshot(p_topic, p_secret) |
the service (anon) |
Returns the snapshot, or null for an unknown device |
realtime_push_send(p_user, p_key, p_title, p_body, p_data, p_silent) |
your backend (service_role) |
Puts a notification in the user's inbox, signals their devices, returns the row id |
realtime_push_mark_read(p_key) |
the app, signed in | Clears that notification on every device |
realtime_push_mark_all_read() |
the app, signed in | Clears all of the user's notifications on every device |
realtime_push_send_test(p_title, p_body) |
the app, signed in | Sends the user a test notification |
realtime_push_snapshot_for(p_user) |
the snapshot | Yours to replace (see below) |
realtime_push_signal(p_users) |
your triggers | Wakes those users' devices |
realtime_push_reply(p_topic, p_secret, p_id, p_text) |
the service (anon) |
Takes a reply typed in the notification |
realtime_push_reply_for(p_user, p_id, p_text) |
the reply | Yours to replace (reply) |
realtime_push_read(p_topic, p_secret, p_id) |
the service (anon) |
Takes "Mark as read" tapped on the notification |
realtime_push_read_for(p_user, p_id) |
the read | Yours to replace (mark as read) |
The phone calls its functions through the Data API with
Content-Profile: public, so public must be among the exposed schemas
(Settings → Data API); it need not be the first.
Self-hosted Supabase: raise the Realtime connection limit first
Every device keeps one Realtime connection open while its screen is on (with
the screen off the processor sleeps and the connection drops within a minute;
the service reconnects when the screen turns on), and an open app's own
Supabase client holds another. So the peak is the phones whose screen is on,
or whose processor another app keeps awake (music, navigation), at the same
time, not every phone: size the limit for your busiest hour, with room to
spare. Self-hosted Realtime accepts 200 concurrent
connections per tenant by default and refuses the rest with 429 Too many connected users. Refused phones get their notifications late: after three
refusals in a row the service waits 5 minutes between tries and reads the
snapshot meanwhile, and lastError() reports the refusal.
# docker-compose, realtime service
environment:
TENANT_MAX_CONCURRENT_USERS: "2000"
With SEED_SELF_HOST=true the tenant is recreated from that variable on every
boot, so set it in the environment, not in the database. On Supabase Cloud the
limit is your plan's Realtime quota.
TENANT_MAX_JOINS_PER_SECOND (100 by default) matters after a Realtime
restart, when every device rejoins. The service spreads its retries randomly,
so a fleet of a few thousand catches up within a minute; raise it if yours is
bigger. TENANT_MAX_EVENTS_PER_SECOND (also 100) counts every signal: an
announcement to the whole fleet at once goes past it and Realtime drops
broadcasts for a while, so raise it or spread such sends out.
Self-hosted Supabase: serve it over https
Over http, anyone on the phone's network reads the device secret (and with
it that user's notifications, until the device is unregistered), every
notification and the topic. So start takes http:// only for local
development. Put TLS in front of the gateway: a reverse proxy with a
certificate (Caddy, nginx, Traefik) that also passes the WebSocket upgrade of
/realtime/v1/. If the certificate comes from your company's internal CA,
which Android does not trust, add that CA to the app's network security
config:
<!-- android/app/src/main/res/xml/network_security_config.xml, with
android:networkSecurityConfig="@xml/network_security_config" on
<application>, and the CA's certificate in res/raw/internal_ca.pem -->
<network-security-config>
<domain-config>
<domain includeSubdomains="true">supabase.example.internal</domain>
<trust-anchors>
<certificates src="@raw/internal_ca" />
</trust-anchors>
</domain-config>
</network-security-config>
2. Flutter #
dependencies:
supabase_realtime_push: ^0.1.0
The plugin's manifest brings its permissions, service and receivers. One
permission it leaves to you on purpose: add
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
to your manifest only if you want the one-tap battery-exemption dialog and
Google Play's policy allows it for your app (see
Battery). Without it,
requestIgnoreBatteryOptimizations() opens the system list instead.
start takes an http:// supabaseUrl only for local development:
localhost, 127.0.0.1, ::1, or 10.0.2.2 (the emulator reaching
supabase start on your computer). Any other host needs https:// (see
Self-hosted Supabase) or the
insecure allowCleartext: true. Cleartext must also be allowed for the host,
which apps targeting Android 9+ block: in your debug build only, set
android:usesCleartextTraffic="true" on <application> in
android/app/src/debug/AndroidManifest.xml, or add a network security config
there that names the host. Otherwise start throws bad_arguments.
The notification channel and the "connected" notification get the plugin's
names in the phone's language unless you pass channelName, connectedTitle
or connectedText to start. They are Android strings, overridden like
Reply's.
3. Register and start (after sign-in) #
final supabase = Supabase.instance.client;
await SupabaseRealtimePush.requestNotificationPermission();
// No "connected" notification once granted; see Battery below.
if (!await SupabaseRealtimePush.isIgnoringBatteryOptimizations()) {
await SupabaseRealtimePush.requestIgnoreBatteryOptimizations();
}
final device = await SupabaseRealtimePush.device();
await supabase.rpc('realtime_push_register', params: device.registerParams);
await SupabaseRealtimePush.start(
supabaseUrl: Uri.parse('https://<ref>.supabase.co'),
publishableKey: '<publishable or anon key>',
channelName: 'Messages',
);
Call start while the app is on screen: Android 12+ refuses to start a
foreground service from the background. The service then survives the app
being closed, the phone rebooting and the app updating.
Run device, realtime_push_register and start again on every app start
while a session exists and status() is unregistered or rejected. A
reinstall or a new phone restores the app's settings from a backup but never
the device pair, so that install reports unregistered until it registers its
own. Never restart a stopped service on your own: stop() was the app's or
the user's choice, such as a "Notifications" switch in your settings.
A user keeps at most 10 devices. Registering an 11th deletes the one that read
a snapshot least recently: that phone clears its notifications and stops with
rejected, and registers again on its next launch if it is still in use. The
limit is the 10 in realtime_push_register.
status() stays running when the user turns the app's notifications off.
areNotificationsEnabled() tells you without prompting, and
openNotificationSettings() opens the page where they turn them back on.
4. Sign out #
final device = await SupabaseRealtimePush.device();
try {
await supabase.rpc('realtime_push_unregister', params: device.unregisterParams);
} catch (_) {
// Offline: sign out anyway. The forgotten pair can no longer read anything.
}
await SupabaseRealtimePush.stop(forgetDevice: true);
await supabase.auth.signOut();
forgetDevice deletes the pair, so the next person to sign in on this phone
gets a new one. Unregistering is best effort: without a network the row stays
on the server, but no phone holds its secret any more.
Sessions also end without your sign-out button: a password change, a revoked session, a refresh that fails. Stop the service on every sign-out, or the next person on a shared phone keeps seeing the previous user's notifications:
supabase.auth.onAuthStateChange.listen((state) {
if (state.event == AuthChangeEvent.signedOut) {
SupabaseRealtimePush.stop(forgetDevice: true);
}
});
The listener runs only while the app runs; the database stops a lost phone
without it. realtime_push_register stores the session the app was signed in
with, and when Supabase Auth deletes that session (a sign-out with scope
global or others from another device, a password change, a revoked
session), the device is deleted and signalled: the phone clears its
notifications and stops with rejected. A session that only times out
(time-box or inactivity) is deleted by Supabase Auth about a day later. A
device registered before this version of realtime_push.sql has no session
until it registers again.
5. Send a notification #
From SQL, any backend, an Edge Function, or a trigger:
select realtime_push_send(
'9f3c…'::uuid, -- the user
'order:42', -- id: same id replaces the notification
'Order shipped',
'It leaves the warehouse today',
'{"route": "/orders/42"}' -- handed back to the app on tap
);
From any backend, over HTTP, with a secret key (sb_secret_…):
curl -X POST 'https://<ref>.supabase.co/rest/v1/rpc/realtime_push_send' \
-H "apikey: $SUPABASE_SECRET_KEY" \
-H 'Content-Profile: public' \
-H 'Content-Type: application/json' \
-d '{"p_user": "9f3c…", "p_key": "order:42", "p_title": "Order shipped",
"p_body": "It leaves the warehouse today", "p_data": {"route": "/orders/42"}}'
It answers with the row id. A secret key goes in apikey only, not in
Authorization: Bearer. The legacy service_role key is a JWT and goes in
both: apikey: <key> and Authorization: Bearer <key>.
From an Edge Function, with
@supabase/server: it takes
the secret key from the function's environment and lets in only callers that
send it in apikey.
// supabase/functions/notify/index.ts, with verify_jwt = false for it in supabase/config.toml
import { withSupabase } from 'npm:@supabase/server@1'
export default {
fetch: withSupabase({ auth: 'secret' }, async (req, ctx) => {
const { user, key, title, body, data } = await req.json()
const { data: id, error } = await ctx.supabaseAdmin.rpc('realtime_push_send', {
p_user: user, p_key: key, p_title: title, p_body: body, p_data: data,
})
return error ? Response.json(error, { status: 500 }) : Response.json({ id })
}),
}
The secret key never ships in the app: sending is server-side only, except a test notification to yourself (below).
From a trigger, for example on every new chat message (messages and its
columns stand for yours):
create or replace function public.notify_new_message()
returns trigger language plpgsql security definer
set search_path = '' as $$
begin
perform public.realtime_push_send(
new.recipient_id, -- the user
'chat:' || new.chat_id, -- one notification per chat
'New message',
new.body,
jsonb_build_object('route', '/chat/' || new.chat_id)
);
return new;
end $$;
create trigger notify_new_message after insert on public.messages
for each row execute function public.notify_new_message();
security definer is needed because realtime_push_send is granted to
service_role only, so a trigger running as the signed-in user would be
refused and fail their insert; with search_path = '', qualify every name with
its schema.
When the user opens it in the app, clear it everywhere:
await supabase.rpc('realtime_push_mark_read', params: {'p_key': 'order:42'});
// A "Mark all as read" button:
await supabase.rpc('realtime_push_mark_all_read');
To check the whole chain from the app, a signed-in user can send themselves a
test notification through the inbox (key realtime_push:test; a new one
replaces the last, and one within 10 s of the last does nothing and returns
null):
await supabase.rpc('realtime_push_send_test');
With the app open it shows in a second or two. With the screen off it can take minutes (see Battery).
Read rows stay so the app can show a history. Trim them on a schedule, for
example with pg_cron:
delete from public.realtime_push_notifications
where read_at < now() - interval '30 days';
Devices go stale too: an app that was uninstalled, or a phone that was reset
or lost, never unregisters. realtime_push_register deletes a user's devices
unseen for 60 days whenever that user registers one, so only the devices of
users who never register again (they uninstalled or left) stay for good.
Delete them on a schedule:
select cron.schedule('realtime-push-stale-devices', '0 3 * * *', $$
delete from public.realtime_push_devices
where seen_at < now() - interval '90 days'
$$);
seen_at is stamped by each snapshot read, at most once a minute; a phone
that is off or offline does not stamp it. A phone that comes back after the
cleanup reads a null snapshot, the service stops with status rejected, and
the app registers it again on its next launch, as
step 3 asks.
6. Handle taps #
final launch = await SupabaseRealtimePush.launchTap(); // opened the app
SupabaseRealtimePush.taps.listen((tap) { // app was running
if (tap.data['route'] case final String route) router.go(route);
});
Your own data instead of the inbox #
The inbox table is a ready-made default. If your notifications already live in your tables (unread chat messages, pending approvals), replace one function and signal from your own triggers:
create or replace function public.realtime_push_snapshot_for(p_user uuid)
returns jsonb language sql stable
set search_path = public, pg_temp as $$
select jsonb_build_object(
'badge', (select count(*) from my_unread_chats(p_user)),
'more', greatest((select count(*) from my_unread_chats(p_user)) - 20, 0),
'notifications', coalesce(jsonb_agg(jsonb_build_object(
'id', 'chat:' || c.id,
'revision', c.last_message_id,
'title', c.title,
'body', c.last_message_text,
'time', (extract(epoch from c.last_message_at) * 1000)::bigint,
'lockScreen', 'redacted',
'publicTitle', 'New message',
'data', jsonb_build_object('route', '/chat/' || c.id)
) order by c.last_message_at desc), '[]'::jsonb))
from (
select * from my_unread_chats(p_user)
order by last_message_at desc
limit 20
) c;
$$;
-- your trigger: security definer, because realtime_push_signal is granted to
-- service_role only and a trigger running as the user would fail the write
create or replace function public.chat_message_signal()
returns trigger language plpgsql security definer
set search_path = '' as $$
begin
perform public.realtime_push_signal(array[new.recipient_id]);
return null;
end $$;
create trigger chat_message_signal after insert on public.chat_messages
for each row execute function public.chat_message_signal();
- Use
p_user, notauth.uid(): the device calls the snapshot without a session. revisionmust grow whenever the notification should alert again.time(milliseconds since the epoch, optional) is shown next to the title. Android sorts the shade by it, so notifications with a time follow it.lockScreen(optional) keeps sensitive content off the lock screen:'redacted'shows onlypublicTitlethere,'hidden'nothing at all. See Security for when Android applies each. The inbox sets neither.- Return at most about 20 notifications (the
limit 20above): Android keeps at most 50 per app and drops the rest without an error. The device keeps the first 50, reads at most 1 MB and drops an entry whosedatais over 4 KB. more(optional) is how many you left out. The device shows it as one quiet "+15 more" at the bottom of the shade, without the badge number, which opens the app; 0 or missing removes it. The inbox sets it to the unread keys past its 20. "+15 more" is the Android stringsupabase_realtime_push_more, translated and overridden like Reply's.- It runs as
anon, whosestatement_timeoutis 3 s on Supabase: past that the snapshot fails every time for that user. Check it withexplain analyzefor your busiest user and index what it filters by. - Running
realtime_push.sqlagain keeps your version; drop the function first to get the default back. - Replace it with
create or replace, which keeps the script's revokes, and leave itsecurity invoker(the default): it already runs with the snapshot function's rights. Adropandcreategets Supabase's default grants, so anyone with the publishable key could call it with any user's id and read their notifications: runrealtime_push.sqlagain afterwards, it revokes them. The same goes forrealtime_push_reply_forandrealtime_push_read_for. - The shape is in doc/contract.md §3.
Reply from the notification #
Like a chat app: the user answers from the notification shade without opening
the app. Add 'reply', true to the notifications that take a reply in your
realtime_push_snapshot_for (the one above), then replace the function that
receives the text:
create or replace function public.realtime_push_reply_for(p_user uuid, p_id text, p_text text)
returns void language plpgsql
set search_path = public, pg_temp as $$
declare
v_chat bigint := substring(p_id from '^chat:(\d+)$')::bigint;
begin
-- p_id comes from the phone: check that this user is in that chat
if not exists (select 1 from chat_members where chat_id = v_chat and user_id = p_user) then
raise exception 'not a member' using errcode = '42501';
end if;
insert into chat_messages (chat_id, sender_id, text) values (v_chat, p_user, p_text);
-- the user has read the chat by replying: clear it, or it comes back
update chat_members set last_read_at = now() where chat_id = v_chat and user_id = p_user;
end $$;
-
The phone removes the notification once the reply is saved. If it is not (offline, an error in your function), the notification says "Not sent", keeps the text under it and offers Reply again.
-
Raise to refuse a reply; it reaches the phone as "Not sent".
-
The ready-made inbox is one-way: it never offers Reply, and the default
realtime_push_reply_forrefuses every reply until you replace it. -
"Reply" and "Not sent" are Android strings, shipped in English, Portuguese, Spanish, French, German and Italian; they follow the phone's language. So are the names
startuses when it gets none:supabase_realtime_push_channel,supabase_realtime_push_connected_titleandsupabase_realtime_push_connected_text. To change them or add another language, define the same names in your app, for exampleandroid/app/src/main/res/values-nl/strings.xml:<resources> <string name="supabase_realtime_push_reply">Beantwoorden</string> <string name="supabase_realtime_push_reply_failed">Niet verzonden</string> </resources>
Mark as read from the notification #
The ready-made inbox offers a "Mark as read" action. The notification leaves
the shade at once, and realtime_push_read marks that key read, which clears
it on the user's other devices too. With your own data, add
'markRead', true in your realtime_push_snapshot_for and replace the
function that does the reading:
create or replace function public.realtime_push_read_for(p_user uuid, p_id text)
returns void language sql
set search_path = public, pg_temp as $$
-- p_id comes from the phone: only ever touch p_user's rows
update chat_members set last_read_at = now()
where chat_id = substring(p_id from '^chat:(\d+)$')::bigint and user_id = p_user;
$$;
- No unlock is needed, unlike Reply: it only takes something away.
- If the call fails (offline, an error in your function), nothing is shown: the notification stays dismissed on this phone, like a swipe, and the other devices keep it.
- "Mark as read" is the Android string
supabase_realtime_push_mark_read, shipped in the same languages as Reply and overridden the same way.
Channels and pictures #
Android lets users mute one kind of notification and keep another, by
channel. Declare yours in start, then pick one per notification in your
realtime_push_snapshot_for:
await SupabaseRealtimePush.start(
supabaseUrl: Uri.parse('https://<ref>.supabase.co'),
publishableKey: '<publishable or anon key>',
channelName: 'Messages',
channels: {
'chat': 'Chat',
'offers': PushChannel('Offers', importance: PushImportance.low),
},
);
'channel', 'offers',
'largeIcon', 'https://<ref>.supabase.co/storage/v1/object/public/avatars/' || c.sender_id || '.png'
- A notification without
channel, or with onestartdid not declare, goes to thechannelNamechannel. - A channel rings, vibrates and pops up over the screen, like the
channelNameone. APushChannelmakes it quieter:PushImportance.mediumrings without popping up,PushImportance.lowshows in the shade without a sound. largeIconis a picture beside the text, such as the sender's avatar:https://only, at most 1 MB. It is downloaded before the notification shows, 5 seconds at most for all of them; if it fails, the notification shows without it.- Build
largeIcononly from storage you control, such as your project's Supabase Storage, never from a URL a user typed (a profile'savatar_url). The phone downloads it with the app closed, so the owner of that server learns each recipient's IP address and when the notification arrived, and a URL to a private address makes the phone send requests inside its own network. The device skips a host that is a private, loopback or link-local IP address. - Android keeps a channel's sound and importance as the user set them, and the importance it was created with: raising it later does nothing, and lowering it works only until the user changes that channel's settings. To change it, give the channel a new id. A channel you stop declaring stays in the app's settings until a reinstall.
- The ready-made inbox sets neither.
The screen the user is looking at #
A notification for the chat that is already open on screen only gets in the
way. Tell the service which snapshot id the user is looking at:
// When the chat screen opens, and again with null when it closes.
await SupabaseRealtimePush.setFocus('chat:$chatId');
await SupabaseRealtimePush.setFocus(null);
- While the app is on screen, that notification leaves the shade and does not ring for new revisions.
- When the app goes to the background the focus stops counting by itself. If the snapshot still lists that notification (the user left without reading), it comes back with the next snapshot, without ringing for what they saw.
- The focus lives in memory: it is gone when the process dies.
Battery and the "connected" notification #
Android stops a background service about a minute after the app leaves the
screen, unless the app is exempt from battery optimization. Without the
exemption the service has to run in the foreground, and Android requires a
notification while it does: the low-priority "connected" one
(connectedTitle, connectedText). So a phone runs in one of three ways:
| "Connected" notification | App closed, screen on | Screen off | |
|---|---|---|---|
| Exempt (recommended) | none | a second or two | up to about 5 minutes (15 in deep Doze) |
| Not exempt (the default) | shown, low priority; the user can hide it | a second or two | up to about 5 minutes, or Doze's next maintenance window |
Not exempt, foregroundService: false |
never | every 5 minutes or more | the same, stretched to an hour or more for an app seldom opened |
With the app open, notifications arrive in a second or two in every mode.
Ask for the exemption when notifications are turned on #
This is the fix for the notification, and it gives the best delivery: exempt apps also keep the network in Doze, Android's idle mode for a phone left still.
if (!await SupabaseRealtimePush.isIgnoringBatteryOptimizations()) {
await SupabaseRealtimePush.requestIgnoreBatteryOptimizations();
}
- Declare
REQUEST_IGNORE_BATTERY_OPTIMIZATIONSin your app'sAndroidManifest.xmlto get the direct one-tap dialog. Without it, the call opens the battery-optimization list, where the user has to find the app. The package never declares it for you (see Google Play below). - A user who grants it later loses the notification at the service's next check, within a few minutes, or at once when the app is next opened.
- Company fleets: many device management (MDM) tools can put an app on the battery-optimization allowlist of every phone, so nobody has to tap anything. Look for "battery optimization" in your MDM's app policies.
Google Play: asking for the exemption directly is
acceptable
for a messaging app only when it cannot use FCM (no Google Play services on
the devices, or a technical dependency on another messaging service). Choosing
not to use FCM is not enough. Apps distributed outside Play, such as company
fleets installing an APK, are not bound by that policy. Apps targeting Android
14+ on Play also declare the remoteMessaging foreground service type in the
Play Console.
Without the exemption #
- The default keeps the connection with the "connected" notification. The
user can turn off just that notification's category and the service keeps
running:
SupabaseRealtimePush.openConnectedNotificationSettings()opens it, so your app can offer a "hide" button. On Android 14 and later the user can also swipe the notification away; it comes back only when the service starts again, after a reboot for instance. Android cuts the network in Doze, so a notification can wait for the next maintenance window. start(foregroundService: false)never shows the notification. The connection is held while the app is open, and Android stops the service about a minute after it closes. From then on an alarm reads the snapshot every 5 minutes or more. Android decides how much more: the check is put off in Doze, and an app the user seldom opens gets about one an hour, or one a day once Android restricts it. Use it when a delay is acceptable and asking for the exemption is not, for example digests or reminders. Chat needs the exemption.
smallIcon is looked up by name. If your release build shrinks resources,
keep that drawable (tools:keep="@drawable/<name>" in res/raw/keep.xml), or
the status bar falls back to the app icon.
Some manufacturers kill background apps more aggressively than Android does. If notifications stop on one brand, see dontkillmyapp.com.
Security #
- The topic is public and the signal carries nothing: knowing a topic tells you only that something changed for that device.
- Content needs the secret, which is 256 random bits; the database stores only its sha256.
- The service never uses the user's session. Sharing the app's refresh token with a second owner would trip GoTrue's refresh-token reuse detection and sign the user out.
- Unregistering a device (or deleting the user) signals it at once: its next
snapshot is
null, and the service clears its notifications and stops. - The lock screen shows a notification's text unless the user chose to hide
sensitive content. For content that must not show to whoever picks up the
phone (a test result, an overdue invoice), set
lockScreenon it in yourrealtime_push_snapshot_for.'hidden'keeps it off a secure lock screen whatever the user's setting.'redacted'shows only itspublicTitle("New message") instead, but only where Android hides private content: when the user's setting hides sensitive content, and while the screen is shared on Android 15+; with the lock screen set to show all content, it shows in full. Any other value counts as'hidden', and a redacted notification with nopublicTitleshows no text there. Without a PIN, pattern or password, everything shows. This follows Android's documentation and is not yet checked on a device; details in doc/contract.md §3. - A device ends with the session it was registered in: signing out everywhere, changing the password or revoking that session deletes and signals it, so a lost phone stops without its app running. A session that ended cannot register a device again, though its access token works until it expires.
Report vulnerabilities privately: see SECURITY.md.
Limits #
- Delivery is instant only with the screen on. With the screen off the phone's processor sleeps, the connection's heartbeat stops and Realtime closes it within a minute. Reconnecting all night would drain the battery, so the service wakes every five minutes instead (up to about fifteen in deep Doze, Android's idle mode for a phone left still) and fetches the snapshot; turning the screen on reconnects at once. FCM does not have this limit, because Google holds that connection for every app.
- Android only.
- One Realtime connection per device while its screen is on (see the self-hosted limit above).
- Supabase Cloud closes public Realtime connections after 24 hours; the service reconnects at once.
- The topic must be public: projects that disabled public Realtime channels cannot use this package.
Troubleshooting #
Call SupabaseRealtimePush.lastError() first. status() says running while
the service is turned on, working or not; lastError() returns its latest
failure and when it happened, the same reason as the log below, or null once
a snapshot works. Show it on a support screen, say.
For more, the service logs under one tag, never the secret or what a notification says:
adb logcat -s SupabaseRealtimePush
A failed call shows the HTTP status and, in brackets, PostgREST's error code when there is one; never the error's message.
| You see | Cause |
|---|---|
snapshot failed: HTTP 404 (PGRST202) |
snapshotFunction names a function that does not exist in public, or realtime_push.sql was not run |
snapshot failed: HTTP 404 (42P01) or (42883) |
Your realtime_push_snapshot_for cannot find a table (42P01) or a function (42883): it runs with an empty search_path, so give it set search_path = public, pg_temp or qualify every name |
snapshot failed: HTTP 406 (PGRST106) |
public is not among the Data API's exposed schemas |
snapshot failed: HTTP 500 (57014) |
Your realtime_push_snapshot_for took longer than anon's statement timeout (3 s on Supabase) for this user: make it faster, usually with an index on what it filters by |
snapshot failed: HTTP 401, no code |
Wrong publishableKey |
reply not sent: HTTP 400 (0A000) |
The default realtime_push_reply_for is still in place: replace it to accept replies |
reply not sent: HTTP 401 (42501) |
Your realtime_push_reply_for refused the reply, as the example does for a non-member |
reply not sent: HTTP 400 (P0001) |
Your realtime_push_reply_for raised an exception without an errcode |
socket failed HTTP 429 |
The Realtime connection limit; see Self-hosted Supabase |
join refused (error) |
Public Realtime channels are turned off in the project |
the server does not know this device |
The device is not registered (status rejected): register it and start again |
foreground not allowed from the background |
Android 12+ killed the service and the app is not exempt; it comes back when the app opens, and until then the watchdog reads the snapshot every few minutes |
UnknownServiceException |
Android blocks cleartext http to the Supabase URL; use https, or allow that host (see Flutter) |
notification not posted: no permission, or nothing arrives while status() is running |
The user turned off the app's notifications or its messages channel: areNotificationsEnabled() is false; offer openNotificationSettings() |
| Nothing at all | start was never called on this install (status() is unregistered), or stop turned it off (stopped) |
Feedback and contributing #
- Bugs and ideas: open an issue.
- Code: see CONTRIBUTING.md.
- Security problems: do not open an issue, see SECURITY.md.
License #
MIT. See LICENSE.
