Introducing a new way to review your PRs.

Read the announcement

capcom6 / android-sms-gateway

The SMS Gateway for Android™ app enables sending and receiving SMS messages through an API that can be accessed directly on the device or via a cloud server when direct device access is not possible.

View on GitHub

20 documents · Updated Nov 20, 2026

docs / event-routing

Event routing and background orchestration

Event routing connects cloud commands, Android message signals, and in-process state changes to background work in the SMS gateway. A transient typed event bus separates producers from feature receivers, while the router translates external commands and the orchestrator controls when the related services and receivers run. This page complements Application lifecycle and module composition, Persistent storage and database evolution, Configuration management and import/export, Message processing, Cloud gateway integration, Webhook delivery, and Notifications.

Event model

The application uses two event forms. An external event is a small command from a cloud transport. An application event is a typed signal used inside the running process.

External event boundary

app/…/ExternalEvent.kt defines an external event with a name and optional text data. Firebase Cloud Messaging and the server-sent event (SSE) service create this form before they pass it to the router. The transport layer accepts known command names and rejects unknown names at the boundary.

The external form keeps cloud transports separate from the feature that performs the work. The router decodes command data only when it creates the matching internal event, so each feature retains ownership of its payload rules.

References: app/…/ExternalEvent.kt• L3-6 app/…/ExternalEventType.kt• L5-20 app/…/PushService.kt• L27-51 app/…/SSEForegroundService.kt• L112-125

Internal event bus

app/…/EventBus.kt provides the process-local event bus. It publishes typed AppEvent values through a shared coroutine flow. Receivers collect only the event types that they own. The bus is transient. It does not store events or replay them for a receiver that starts later.

The base EventsReceiver gives each feature a managed subscription. Starting a receiver replaces its prior collection. Stopping it cancels the collection, which lets the orchestrator match event handling to the lifetime of the owning service.

References: app/…/EventBus.kt• L8-23 app/…/AppEvent.kt• L3-6 app/…/EventsReceiver.kt• L11-29 app/…/Module.kt• L5-7

Command routing

EventsRouter is the single translation point from external command names to internal event types. It does not perform the command itself. It publishes an event and lets the owning receiver start the correct background work.

External commandInternal eventMain reaction
MessageEnqueuedMessageEnqueuedEventPull cloud messages into local message work.
WebhooksUpdatedWebhooksUpdatedEventRefresh cloud-owned webhook records.
MessagesExportRequestedMessagesExportRequestedEventExport selected SMS or MMS records.
SettingsUpdatedSettingsUpdatedEventApply a cloud settings refresh.
MessageCancelledMessageCancelledEventCancel matching local pending work.

The router handles commands on an I/O scope. Commands that need data fail when their payload is absent or invalid. Export requests carry the time range, message selection, and webhook delivery choice needed by the receiver service. The export event also keeps compatibility with the older triggerWebhooks field.

References: app/…/EventsRouter.kt• L16-55 app/…/MessagesExportRequestedEvent.kt• L11-52

Gateway event receiver

The gateway receiver turns routed cloud commands and shared state signals into synchronization work. It starts message pulls for enqueue and ping events. It refreshes settings or webhooks when their definitions change. It reports eligible message changes to the cloud and applies remote cancellation to local pending work.

Gateway enablement gates these reactions. A disabled gateway does not act on cloud work. After device registration, the receiver starts the SSE service when no Firebase Cloud Messaging token is stored. After a device key rotation, it starts registration work so the changed device identity can be registered again.

References: app/…/EventsRouter.kt• L21-53 app/…/EventsReceiver.kt• L26-131 app/…/GatewayService.kt• L44-65

Receiver event receiver

The receiver event receiver owns remote export commands. It passes the request range, message types, and webhook delivery mode to the receiver service. That service reads the phone inbox and can emit individual or batch webhook events. This keeps an on-demand export separate from normal live SMS and MMS intake.

Android message signals enter through the SMS and MMS receivers or through the MMS inbox observer. The SMS receiver accepts text and data SMS broadcasts, joins multi-part content, records the sender and time, identifies the subscription, and passes one normalized inbox message to ReceiverService. The MMS receiver handles notification broadcasts and passes normalized MMS headers to the same service. After the phone downloads an MMS, MmsContentObserver watches the inbox for completed rows and reads the message through MmsContentReader; it also catches up rows that arrived while the process was stopped. The reader keeps large parts out of memory and marks content above the configured inline limit as omitted. ReceiverService then deduplicates the message, saves it, queues gateway work, and can create an individual or batch webhook event.

References: app/…/EventsReceiver.kt• L12-31 app/…/ReceiverService.kt• L41-57 app/…/ReceiverService.kt• L102-127 app/…/MessagesReceiver.kt• L18-65 app/…/MmsReceiver.kt• L26-105 app/…/MmsContentObserver.kt• L26-67 app/…/MmsContentObserver.kt• L101-225 app/…/MmsContentReader.kt• L12-23 app/…/MmsContentReader.kt• L96-175 app/…/ReceiverSettings.kt• L15-30 app/…/InboxMessage.kt• L52-76 app/…/MMSParser.kt• L24-62 app/…/MessagesRoutes.kt• L264-284

Message state receiver

The Android message-state receiver carries sent, delivered, and MMS-sent signals from the telephony work back into message processing. It keeps the broadcast work alive long enough for MessagesService to process the signal. If processing fails, it records an error and still releases the broadcast result.

This path is separate from the internal event bus. Android sends the signal as a broadcast, and message processing then publishes a typed state event for gateway, webhook, and user-interface consumers.

References: app/…/EventsReceiver.kt• L18-41 app/…/EventsReceiver.kt• L43-68 app/…/MessagesService.kt• L367-392

State event distribution

Not every application event comes from the external router. Message processing, health checks, device registration, and local network discovery publish events directly to the bus. Several receivers can observe one event, so one state change can update cloud state, create a webhook, and refresh the user interface without direct calls between those areas.

Message state events

MessageStateChangedEvent describes a message or recipient state change. It carries its source, recipients, SIM, part count, and optional error. The message service emits it after it changes stored state.

The gateway receiver reports only cloud- or gateway-owned changes. The webhook receiver turns terminal sent, delivered, failed, and cancelled states into webhook events for each destination. The message service owns local state. The gateway owns cloud reporting. The webhook service owns external delivery.

References: app/…/MessageStateChangedEvent.kt• L7-19 app/…/MessagesService.kt• L367-392 app/…/EventsReceiver.kt• L40-53 app/…/EventsReceiver.kt• L32-93

Health and lifecycle events

The ping service publishes health results as PingEvent. The gateway receiver uses that signal to request another cloud message pull. The webhook receiver can expose the same health result as a system-ping webhook. Device registration and local IP discovery publish separate signals that the home screen uses to show connection and identity data.

These paths keep internal observation separate from external delivery. The bus carries state within the process. A gateway, webhook, or user-interface consumer decides whether that state needs a network action or a display update.

References: app/…/PingForegroundService.kt• L49-65 app/…/EventsReceiver.kt• L54-126 app/…/EventsReceiver.kt• L20-29 app/…/GatewayService.kt• L147-193 app/…/HomeFragment.kt• L174-278

Background orchestration

OrchestratorService owns the application runtime boundary. It starts and stops the feature services and receivers that support message work, cloud access, local access, webhook delivery, health checks, registration, and logs. Feature settings still decide whether an individual service performs work.

Runtime coordination

On an allowed start, the orchestrator starts core services first. It then attempts the local server and ping service. It registers phone message receivers and emits an application-started webhook with the active SIM cards. A stop request releases the registrations and background services through the same boundary.

The autostart argument separates an automatic request from a user request. Automatic startup stops when the app-wide autostart setting is off. A user start can still run the configured services. The application process and boot receiver use this same coordinator instead of separate startup sequences.

References: app/…/OrchestratorService.kt• L19-83 app/…/App.kt• L39-75 app/…/BootReceiver.kt• L10-26

Worker activation

Event receivers start scheduled or one-time workers instead of doing long network or queue work inside event collection. Message pulls reconcile cloud work with local messages. State workers report cloud-owned results. Settings and webhook workers refresh remote data. Webhook workers deliver queued external events. Device key rotation starts registration work so cloud identity stays aligned with the device.

This split keeps event handling short. Each work type can then apply its own storage, retry, and network rules. See Webhook delivery for the durable webhook queue and Cloud gateway integration for cloud synchronization.

References: app/…/EventsReceiver.kt• L30-126 app/…/WebHooksService.kt• L36-46 app/…/WebHooksService.kt• L126-169 app/…/MessagesService.kt• L82-92

Notification signals

Notifications give users a visible signal for work that can continue after the screen closes. NotificationsService creates the common notification form used by foreground services and workers. Settings changes and new incoming-SMS webhook registrations also use it to tell the user that a stored choice or privacy-sensitive registration needs attention.

Notifications are not a second event bus. A service or worker calls the notification service when its own state needs to be visible. The event bus remains the path for typed coordination between application features.

References: app/…/NotificationsService.kt• L13-96 app/…/SettingsService.kt• L39-63 app/…/WebHooksService.kt• L105-110 app/…/WebHooksService.kt• L213-220

Coordination flow

The system combines external command routing with direct internal event publication. This diagram shows how both paths reach feature work while the orchestrator controls whether receivers and services are active.

flowchart LR
    Cloud[SSE or FCM] --> External[External event]
    External --> Router[EventsRouter]
    Router --> Bus[EventBus]
    Android[Android SMS and MMS signals] --> Intake[Message intake]
    Android --> State[Message state processing]
    Intake --> Local[Local message work]
    State --> Bus
    Health[Health result] --> Bus
    Bus --> Gateway[Gateway event receiver]
    Bus --> Receiver[Receiver event receiver]
    Bus --> Webhooks[Webhook event receiver]
    Bus --> UI[User interface observers]
    Gateway --> GatewayWork[Pull, sync, cancel, or report workers]
    Receiver --> Export[Inbox export]
    Webhooks --> Delivery[Webhook queue]
    Orchestrator[OrchestratorService] --> Gateway
    Orchestrator --> Receiver
    Orchestrator --> Webhooks
    Orchestrator --> Runtime[Background services]

The event bus coordinates only work in the current process. Durable message, webhook, and configuration state belongs to its own storage and service path. See Persistent storage and database evolution and Configuration management and import/export.

References: app/…/EventBus.kt• L8-23 app/…/EventsRouter.kt• L16-55 app/…/OrchestratorService.kt• L19-83 app/…/MessagesReceiver.kt• L18-65 app/…/MmsReceiver.kt• L26-105 app/…/MmsContentObserver.kt• L26-67 app/…/EventsReceiver.kt• L18-41

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep each external command name aligned across SSE data, FCM data, ExternalEventType, and EventsRouter.
  • Keep command payload fields aligned between the router, event parser, export request, and cloud command contract.
  • When adding an AppEvent, add its collector to the owning receiver and pair receiver start and stop behavior.
  • When changing Android SMS or message-state broadcast actions, keep registration filters and processing paths aligned.
  • When changing MMS broadcast filters or notification fields, keep PDU parsing, normalized inbox data, and receiver-service intake aligned.
  • When changing MMS content observation or high-water-mark rules, preserve catch-up behavior and the link between processed rows and ReceiverService.
  • When changing MMS inline limits, keep settings validation, bounded content reads, omitted attachment metadata, and export budgets aligned.
  • When changing message state meaning or source values, review both cloud state reporting and webhook event creation.
  • When changing device identity or key rotation, keep the rotation event, gateway receiver, and registration request aligned.
  • When adding a long-running service or receiver, add it to both orchestrator start and stop paths.
  • Keep notification IDs and foreground-service notification paths distinct when new background work becomes user-visible.

Important failure modes

TriggerConsequenceGuard
An event is emitted while its feature receiver is stoppedThe transient event is not replayed, so the reaction does not runStart receivers with their owning service. Use scheduled workers or durable records for recovery.
A remote command name is absent or unknownThe transport cannot create the intended command eventKeep cloud names in ExternalEventType and preserve transport validation.
A command that needs data has missing or invalid payload dataThe router cannot create the internal event, so no worker startsKeep required fields aligned with EventsRouter and the event parser.
The gateway is disabled when a gateway event arrivesPull, sync, cancellation, registration, or state-report work is skippedCheck gateway enablement before relying on remote commands or state delivery.
A device key rotates without a registration reactionCloud identity can remain out of date after the local key changesPreserve the key-rotation event path to RegistrationWorker.
An Android message broadcast has an unsupported action or no messagesNo local message work is createdKeep SMS and data-SMS registration filters aligned with MessagesReceiver.
Message-state processing failsThe state change is not applied, but the broadcast result is still releasedReview error logging and state handling when changing MessagesService or the broadcast contract.
MMS access is denied or the observer starts without the required permissionNew MMS rows are not read into local message workKeep permission checks, warning logs, and observer start behavior aligned.
An MMS row is observed before its parts are readyThe message can lack its sender or contentPreserve bounded retry behavior before passing the message to ReceiverService.
An MMS part exceeds the inline limit or the export budgetThe message keeps metadata but webhook or cloud payloads omit inline bytesKeep the configured limit, bounded reads, omitted markers, and attachment endpoint behavior aligned.
A foreground service start is rejected while the app is in the backgroundLocal server or ping work may remain stopped while other startup work continuesKeep this startup group isolated and retain warning-level reporting.
A message state event has a local sourceThe gateway does not report it to the cloudKeep source ownership correct when creating messages and retain the gateway source filter.

Key files

FileWhy to read it
app/…/EventBus.ktDefines the transient typed channel shared by feature modules.
app/…/EventsReceiver.ktDefines how feature subscriptions start and stop.
app/…/EventsRouter.ktDefines the external-command to internal-event mapping.
app/…/ExternalEventType.ktDefines the cloud command names accepted by the application.
app/…/EventsReceiver.ktShows how gateway commands, identity changes, and shared state events activate cloud work.
app/…/EventsReceiver.ktShows how health and message state become webhook events.
app/…/EventsReceiver.ktShows how a routed export command reaches inbox processing.
app/…/ReceiverService.ktShows how normalized SMS and MMS data becomes stored message work and webhook payloads.
app/…/MessagesReceiver.ktShows how Android SMS broadcasts become normalized inbox work.
app/…/MmsReceiver.ktShows how Android MMS notifications become normalized MMS inbox work.
app/…/MmsContentObserver.ktShows how downloaded MMS rows are detected and caught up after process downtime.
app/…/MmsContentReader.ktShows how MMS text and attachments become bounded, normalized content.
app/…/BoundedStreamReader.ktDefines the memory bound used when reading MMS part data.
app/…/ReceiverSettings.ktDefines the receiver controls for content-provider intake and inline MMS data.
app/…/InboxMessage.ktDefines the normalized SMS and MMS forms shared by intake and export.
app/…/EventsReceiver.ktShows how Android sent and delivery signals reach message state processing.
app/…/OrchestratorService.ktDefines the start and stop boundary for background capabilities.
app/…/PushService.ktShows the Firebase command ingress path.
app/…/SSEForegroundService.ktShows the SSE command ingress path and its handoff to the router.
app/…/NotificationsService.ktDefines the user-visible signals used by background work.