feat(android): foreground service keeps the onion reachable through Doze #60

Merged
sirius merged 2 commits from feat/android-foreground-keepalive into main 2026-09-12 22:08:46 +00:00
Owner

Stacked on #49

Card t_5bf32cd3. feat/tor-lifecycle (PR #49, Wire.shutdown/flush/torState) is not on main
yet, and this card cannot work without it: git rev-list --count origin/main..origin/feat/tor-lifecycle
= 3. Base is therefore feat/tor-lifecycle @ 48c06df, not main. Retarget to main after #49 lands.

What this does

Keeps the in-process Arti node published after the screen goes off, behind an ongoing
notification, and stops the ViewModel from tearing down a node it does not exclusively own.

  • keepalive/NodeLifetime.kt — pure policy for the node's lifetime. Anchors (UI, KEEP_ALIVE)
    are reported in, a NodeAction (Keep/Flush/Stop) comes out. Losing the UI anchor while a
    keep-alive is still held returns Flush, not Stop — that is this card in one branch.
  • keepalive/NodeHost.kt — process-wide owner of the single Wire. Only this object calls
    flush()/shutdown(). The ViewModel and the service both report transitions here.
  • keepalive/KeepAliveService.kt — the foreground service: started on unlock, stopped by Lock or
    by the notification's action.
  • WireViewModel — no longer holds wire and no longer calls shutdown(). lock() stops the
    service first, then asks the policy to tear the node down; onCleared() reports "UI gone" and
    lets the policy decide.

Why this shape (and not "the service owns the Wire")

WireViewModel, MainActivity, RosterScreen, UnlockScreen, strings.xml,
AndroidManifest.xml. No new Gradle dependency and no libs.versions.toml change: Service,
Notification/NotificationChannel/NotificationCompat come from the platform plus
androidx.core, which is already on the classpath. LifecycleService would have bought a
lifecycleScope this service does not need, so it was left out to avoid a new dependency.

Ownership audit, because "no double ownership" is the bug this card names:

$ grep -rn "\.shutdown()" android/app/src
keepalive/NodeHost.kt:150:            runCatching { dying.shutdown() }
$ grep -rn "\.flush()" android/app/src
keepalive/NodeHost.kt:131:            NodeAction.Flush -> scope.launch { runCatching { wire?.flush() } }
keepalive/NodeHost.kt:146:            runCatching { dying.flush() }

One shutdown(), two flush(), all three inside NodeHost. WireViewModel.onCleared() used to
be a shutdown site; it now reports a transition.

Re-unlock with a node the service kept alive adopts the live Wire (WireViewModel.init,
openWith) instead of reopening it — the live node holds the sqlite file and Arti's state lock,
so a racing open fails. NodeHost also moved the SDK's blocking openWire() onto
Dispatchers.IO: on this base it ran inside viewModelScope.launch on the main thread, which is
minutes of Tor bootstrap on the main thread.

FGS type: specialUse, not dataSync

The card suggested dataSync. The SDK documents dataSync as "data transfer operations"
(upload/download, backup/restore, import/export, local file processing) and the official
data-transfer alternatives guide
routes those to WorkManager or a user-initiated transfer job — both assume a transfer with an end.
This is an inbound onion service held open plus a retry queue drained in the background, with no
user-initiated transfer and no progress to report, so specialUse ("valid foreground service use
cases that aren't covered by the other types") is the honest declaration. It costs a Play Console
justification, which the manifest carries as PROPERTY_SPECIAL_USE_FGS_SUBTYPE; dataSync would
cost a declaration that does not describe the app.

Also rejected: remoteMessaging (message transfer when switching devices) and connectedDevice
(external accessories; would also drag in CHANGE_NETWORK_STATE).

minSdk 26 / targetSdk 36 unchanged, so FOREGROUND_SERVICE_SPECIAL_USE is declared next to
FOREGROUND_SERVICE.

The notification, and what it is allowed to say

Channel keep-alive, IMPORTANCE_LOW, no sound, no badge, ongoing. Text names the moving parts
instead of saying "running in the background":

OnionWire is reachable
Tor and the outbox are running so peers can reach wd2zaqo3ge…
[ Stop keep-alive ]

Only the first ten characters of the v3 locator: a notification body is lock-screen public, and
the locator is the address you do not want photographed. The action is labelled Stop keep-alive,
not "Lock", because that is exactly what it does — it drops the service's anchor. If the app is
still on screen (the UI anchor) the node stays up, and the roster says
"Reachable only while this app is open." Pressing Lock in the app is what tears the node down.

START_NOT_STICKY: the passphrase is not held in memory after unlock, so a sticky restart would
come back with no node behind it and a notification claiming a reachable onion that is not there.

POST_NOTIFICATIONS

Declared, requested when the node becomes reachable (not at first launch), via
ActivityResultContracts.RequestPermission(). Denial is not fatal: the service still starts
and the FGS still runs — per the notification-permission docs, "if the user denies the notification
permission, they still see notices related to foreground services in the Task Manager but don't see
them in the notification drawer" — and the roster says so.

One thing the first cut got wrong and this PR fixes: Android does not retroactively post an FGS
notification that was suppressed while the permission was denied, so granting after the unlock left
the shade empty. onNotificationPermissionChanged() now re-announces the keep-alive. Likewise
startForeground() itself is wrapped: on API 31+ a background start throws
ForegroundServiceStartNotAllowedException, which is caught, recorded as
KeepAliveStatus.Unavailable, and shown on the roster instead of killing the process.

Verified

Build + unit tests (arm64-v8a, the shipped ABI)

$ CARGO_TARGET_DIR=/var/tmp/ow-t_5bf32cd3 ./gradlew --no-daemon :app:assembleDebug :app:testDebugUnitTest -Ponionwire.abis=arm64-v8a
BUILD SUCCESSFUL in 18s
67 actionable tasks: 3 executed, 64 up-to-date
EXIT=0

app-debug.apk — 46,925,810 bytes, sha256 7847b495965b45397082056a6b620e557101ad0e5cc0e024cc8f9dd7c80464c3,
packaging lib/arm64-v8a/libonionwire_sdk.so (34,439,472 bytes).

$ # app/build/test-results/testDebugUnitTest
com.siriusdevops.onionwire.crypto.StoreSecretTest        11 tests, 0 failures
com.siriusdevops.onionwire.crypto.StoredPassphraseStoreTest 9 tests, 0 failures
com.siriusdevops.onionwire.keepalive.NodeLifetimeTest     9 tests, 0 failures
com.siriusdevops.onionwire.ui.InviteAddFlowTest           5 tests, 0 failures
TOTAL 34 tests, 0 failures

The 9 new cases are the service-lifetime machine with no device: ui_detach_with_no_keep_alive_stops_the_node,
keep_alive_anchor_survives_ui_detach_and_only_flushes, losing_the_last_anchor_stops_the_node,
service_stopping_while_the_ui_is_up_keeps_the_node, repeated_anchor_loss_is_idempotent,
lock_drops_every_anchor, re_unlock_after_lock_starts_from_a_clean_slate,
re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it, transitions_on_a_closed_node_do_nothing.

On a device — API 35 emulator (ow35), x86_64 debug build

Built -Ponionwire.abis=x86_64 for the emulator (the arm64 APK will not install on an x86_64 AVD).
Real unlock with a real passphrase, so this was a real Arti bootstrap and a real onion publish;
the identity is 0bed566d… and the locator wd2zaqo3gemlzwmnj3vuhd2k7vfvevlnbpzlfwnvmpwrbdx44xuaklad.onion.

Service in the foreground, notification posted:

$ adb shell dumpsys activity services com.siriusdevops.onionwire.debug
  * ServiceRecord{2be6fa2 u0 com.siriusdevops.onionwire.debug/com.siriusdevops.onionwire.keepalive.KeepAliveService c:com.siriusdevops.onionwire.debug}
    isForeground=true foregroundId=1 types=0x40000000 foregroundNoti=Notification(channel=keep-alive shortcut=null contentView=null vibrate=null sound=null defaults=0 flags=ONGOING_EVENT|ONLY_ALERT_ONCE|NO_CLEAR|FOREGROUND_SERVICE color=0x00000000 category=service actions=1 vis=PRIVATE)
 startCommandResult=2

types=0x40000000 is FOREGROUND_SERVICE_TYPE_SPECIAL_USE; startCommandResult=2 is
START_NOT_STICKY. The notification itself:

$ adb shell dumpsys notification --noredact | grep -A14 pkg=com.siriusdevops.onionwire.debug
  NotificationRecord(… channel=keep-alive … flags=ONGOING_EVENT|ONLY_ALERT_ONCE|NO_CLEAR|FOREGROUND_SERVICE … actions=1 …)
    android.title=String (OnionWire is reachable)
    android.text=String (Tor and the outbox are running so peers can reach wd2zaqo3ge…)
  NotificationChannel{mId='keep-alive', mName=Node keep-alive, mImportance=2, … mShowBadge=false …}

Backgrounding (HOME, 70 s, then re-checked):

isForeground=true foregroundId=1 types=0x40000000 …
u0_a209  5578 … com.siriusdevops.onionwire.debug      # same pid, not killed

Doze (input keyevent 26 + dumpsys deviceidle force-idle, 3 minutes):

  mScreenOn=false
  mState=IDLE mLightState=OVERRIDE
--- after 3 min:
  mState=IDLE
  isForeground=true foregroundId=1 types=0x40000000 …
  u0_a209  5578 … com.siriusdevops.onionwire.debug
  notification records for channel=keep-alive: 1
$ dumpsys deviceidle unforce
Light state: ACTIVE, deep state: ACTIVE

and on wake, relaunching the app showed the same onion, i.e. the node was never torn down and
re-bootstrapped.

The notification action, tapped in the shade (expanded notification showed
OnionWire is reachable / Tor and the outbox are running so peers can reach wd2zaqo3ge… /
[Stop keep-alive] at bounds=[147,1329][460,1455]):

$ adb shell input tap 303 1392
--- service records remaining: 0
--- notification records: 0
--- process: 1

and the roster then read Reachable only while this app is open. — the node stayed up under the UI
anchor, exactly as the policy says. Pressing Lock in the app bar afterwards returned to the
unlock screen with the service gone and nothing in logcat but the usual frames.

Denied-permission path, observed for real: with POST_NOTIFICATIONS still at its default
(fresh install), the unlock started the service and dumpsys activity services reported
isForeground=true while the shade had no OnionWire notification — the documented
"Task Manager, not the drawer" behaviour, not a crash.

android:exported="false" on the service holds: adb shell am start-foreground-service -n …KeepAliveService -a …STOP is refused with Error: Requires permission not exported from uid 10209.

Not verified

  • Reachability from a peer while backgrounded. I confirmed the node, the process and the
    notification survive backgrounding and forced deep Doze, but I had no second OnionWire peer
    dialling wd2zaqo3… while the screen was off, so "the descriptor stays reachable under Doze"
    is an inference from "the node was never torn down", not a measured fetch.
  • The ViewModel adopt path on a device. It is covered by the policy unit test
    (re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it), but I could not get the
    emulator to destroy the activity while keeping the process alive (always_finish_activities=1
    did not destroy it in practice), so the VM-level adoption was not exercised live.
  • Long-duration Doze. 3 minutes, not a 6-hour overnight idle, and the emulator reports
    mCharging=true (Doze was forced, not earned). I would not claim a battery number from this.
  • No OEM device: Xiaomi/Huawei/Samsung battery managers kill more than AOSP Doze does, and nothing
    here has been run against one.

Files touched

 android/app/src/main/AndroidManifest.xml                          |  42 +++-
 android/app/src/main/java/.../MainActivity.kt                     |  28 ++-
 android/app/src/main/java/.../WireViewModel.kt                    | 222 ++++++-----
 android/app/src/main/java/.../keepalive/KeepAliveService.kt       | 181 ++++++++++
 android/app/src/main/java/.../keepalive/NodeHost.kt               | 153 +++++++++
 android/app/src/main/java/.../keepalive/NodeLifetime.kt           |  99 ++++++
 android/app/src/main/java/.../ui/RosterScreen.kt                  |   9 +
 android/app/src/main/java/.../ui/UnlockScreen.kt                  |   4 +-
 android/app/src/main/res/drawable/ic_stat_onion.xml               |  17 ++
 android/app/src/main/res/values/strings.xml                       |  16 +
 android/app/src/test/java/.../keepalive/NodeLifetimeTest.kt       | 130 +++++++++
 11 files changed, 814 insertions(+), 87 deletions(-)

README.md untouched (owned by #38); src/**, crates/**, .forgejo/workflows/** untouched.
crates/onionwire-sdk/Cargo.lock is rewritten by any cargo ndk build in the tree and was
reverted before committing — it is out of scope here.

README (deferred)

No change needed: README.md on this base makes no claim about background lifetime or about
INTERNET being the only permission, so nothing in it is now false. The two stale statements were
the app manifest comment and the unlock screen's "INTERNET is the only permission this app
requests." line; both are fixed in this PR. If you want the keep-alive documented in README at
all, the one sentence I would add under the Android section is:

On unlock the app starts a foreground service with an ongoing notification (specialUse) so
peers can still reach your onion while the screen is off; Lock, or the notification's
Stop keep-alive action, ends it.

## Stacked on #49 Card t_5bf32cd3. `feat/tor-lifecycle` (PR #49, `Wire.shutdown`/`flush`/`torState`) is **not on `main`** yet, and this card cannot work without it: `git rev-list --count origin/main..origin/feat/tor-lifecycle` = 3. Base is therefore `feat/tor-lifecycle` @ `48c06df`, not `main`. Retarget to `main` after #49 lands. ## What this does Keeps the in-process Arti node published after the screen goes off, behind an ongoing notification, and stops the ViewModel from tearing down a node it does not exclusively own. - `keepalive/NodeLifetime.kt` — pure policy for the node's lifetime. Anchors (`UI`, `KEEP_ALIVE`) are reported in, a `NodeAction` (`Keep`/`Flush`/`Stop`) comes out. Losing the UI anchor while a keep-alive is still held returns `Flush`, not `Stop` — that is this card in one branch. - `keepalive/NodeHost.kt` — process-wide owner of the single `Wire`. Only this object calls `flush()`/`shutdown()`. The ViewModel and the service both report transitions here. - `keepalive/KeepAliveService.kt` — the foreground service: started on unlock, stopped by Lock or by the notification's action. - `WireViewModel` — no longer holds `wire` and no longer calls `shutdown()`. `lock()` stops the service first, then asks the policy to tear the node down; `onCleared()` reports "UI gone" and lets the policy decide. ## Why this shape (and not "the service owns the Wire") `WireViewModel`, `MainActivity`, `RosterScreen`, `UnlockScreen`, `strings.xml`, `AndroidManifest.xml`. No new Gradle dependency and no `libs.versions.toml` change: `Service`, `Notification`/`NotificationChannel`/`NotificationCompat` come from the platform plus `androidx.core`, which is already on the classpath. `LifecycleService` would have bought a `lifecycleScope` this service does not need, so it was left out to avoid a new dependency. Ownership audit, because "no double ownership" is the bug this card names: ``` $ grep -rn "\.shutdown()" android/app/src keepalive/NodeHost.kt:150: runCatching { dying.shutdown() } $ grep -rn "\.flush()" android/app/src keepalive/NodeHost.kt:131: NodeAction.Flush -> scope.launch { runCatching { wire?.flush() } } keepalive/NodeHost.kt:146: runCatching { dying.flush() } ``` One `shutdown()`, two `flush()`, all three inside `NodeHost`. `WireViewModel.onCleared()` used to be a shutdown site; it now reports a transition. Re-unlock with a node the service kept alive **adopts** the live `Wire` (`WireViewModel.init`, `openWith`) instead of reopening it — the live node holds the sqlite file and Arti's state lock, so a racing open fails. `NodeHost` also moved the SDK's blocking `openWire()` onto `Dispatchers.IO`: on this base it ran inside `viewModelScope.launch` on the main thread, which is minutes of Tor bootstrap on the main thread. ## FGS type: `specialUse`, not `dataSync` The card suggested `dataSync`. The SDK documents `dataSync` as "data transfer operations" (upload/download, backup/restore, import/export, local file processing) and the official [data-transfer alternatives guide](https://developer.android.com/develop/background-work/background-tasks/data-transfer-options) routes those to WorkManager or a user-initiated transfer job — both assume a transfer with an end. This is an inbound onion service held open plus a retry queue drained in the background, with no user-initiated transfer and no progress to report, so `specialUse` ("valid foreground service use cases that aren't covered by the other types") is the honest declaration. It costs a Play Console justification, which the manifest carries as `PROPERTY_SPECIAL_USE_FGS_SUBTYPE`; `dataSync` would cost a declaration that does not describe the app. Also rejected: `remoteMessaging` (message transfer when switching devices) and `connectedDevice` (external accessories; would also drag in `CHANGE_NETWORK_STATE`). `minSdk 26` / `targetSdk 36` unchanged, so `FOREGROUND_SERVICE_SPECIAL_USE` is declared next to `FOREGROUND_SERVICE`. ## The notification, and what it is allowed to say Channel `keep-alive`, `IMPORTANCE_LOW`, no sound, no badge, ongoing. Text names the moving parts instead of saying "running in the background": > **OnionWire is reachable** > Tor and the outbox are running so peers can reach wd2zaqo3ge… > [ Stop keep-alive ] Only the first ten characters of the v3 locator: a notification body is lock-screen public, and the locator is the address you do not want photographed. The action is labelled **Stop keep-alive**, not "Lock", because that is exactly what it does — it drops the service's anchor. If the app is still on screen (the UI anchor) the node stays up, and the roster says "Reachable only while this app is open." Pressing Lock in the app is what tears the node down. `START_NOT_STICKY`: the passphrase is not held in memory after unlock, so a sticky restart would come back with no node behind it and a notification claiming a reachable onion that is not there. ## POST_NOTIFICATIONS Declared, requested when the node becomes reachable (not at first launch), via `ActivityResultContracts.RequestPermission()`. Denial is **not** fatal: the service still starts and the FGS still runs — per the notification-permission docs, "if the user denies the notification permission, they still see notices related to foreground services in the Task Manager but don't see them in the notification drawer" — and the roster says so. One thing the first cut got wrong and this PR fixes: Android does **not** retroactively post an FGS notification that was suppressed while the permission was denied, so granting after the unlock left the shade empty. `onNotificationPermissionChanged()` now re-announces the keep-alive. Likewise `startForeground()` itself is wrapped: on API 31+ a background start throws `ForegroundServiceStartNotAllowedException`, which is caught, recorded as `KeepAliveStatus.Unavailable`, and shown on the roster instead of killing the process. ## Verified ### Build + unit tests (arm64-v8a, the shipped ABI) ``` $ CARGO_TARGET_DIR=/var/tmp/ow-t_5bf32cd3 ./gradlew --no-daemon :app:assembleDebug :app:testDebugUnitTest -Ponionwire.abis=arm64-v8a BUILD SUCCESSFUL in 18s 67 actionable tasks: 3 executed, 64 up-to-date EXIT=0 ``` `app-debug.apk` — 46,925,810 bytes, sha256 `7847b495965b45397082056a6b620e557101ad0e5cc0e024cc8f9dd7c80464c3`, packaging `lib/arm64-v8a/libonionwire_sdk.so` (34,439,472 bytes). ``` $ # app/build/test-results/testDebugUnitTest com.siriusdevops.onionwire.crypto.StoreSecretTest 11 tests, 0 failures com.siriusdevops.onionwire.crypto.StoredPassphraseStoreTest 9 tests, 0 failures com.siriusdevops.onionwire.keepalive.NodeLifetimeTest 9 tests, 0 failures com.siriusdevops.onionwire.ui.InviteAddFlowTest 5 tests, 0 failures TOTAL 34 tests, 0 failures ``` The 9 new cases are the service-lifetime machine with no device: `ui_detach_with_no_keep_alive_stops_the_node`, `keep_alive_anchor_survives_ui_detach_and_only_flushes`, `losing_the_last_anchor_stops_the_node`, `service_stopping_while_the_ui_is_up_keeps_the_node`, `repeated_anchor_loss_is_idempotent`, `lock_drops_every_anchor`, `re_unlock_after_lock_starts_from_a_clean_slate`, `re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it`, `transitions_on_a_closed_node_do_nothing`. ### On a device — API 35 emulator (`ow35`), x86_64 debug build Built `-Ponionwire.abis=x86_64` for the emulator (the arm64 APK will not install on an x86_64 AVD). Real unlock with a real passphrase, so this was a real Arti bootstrap and a real onion publish; the identity is `0bed566d…` and the locator `wd2zaqo3gemlzwmnj3vuhd2k7vfvevlnbpzlfwnvmpwrbdx44xuaklad.onion`. Service in the foreground, notification posted: ``` $ adb shell dumpsys activity services com.siriusdevops.onionwire.debug * ServiceRecord{2be6fa2 u0 com.siriusdevops.onionwire.debug/com.siriusdevops.onionwire.keepalive.KeepAliveService c:com.siriusdevops.onionwire.debug} isForeground=true foregroundId=1 types=0x40000000 foregroundNoti=Notification(channel=keep-alive shortcut=null contentView=null vibrate=null sound=null defaults=0 flags=ONGOING_EVENT|ONLY_ALERT_ONCE|NO_CLEAR|FOREGROUND_SERVICE color=0x00000000 category=service actions=1 vis=PRIVATE) startCommandResult=2 ``` `types=0x40000000` is `FOREGROUND_SERVICE_TYPE_SPECIAL_USE`; `startCommandResult=2` is `START_NOT_STICKY`. The notification itself: ``` $ adb shell dumpsys notification --noredact | grep -A14 pkg=com.siriusdevops.onionwire.debug NotificationRecord(… channel=keep-alive … flags=ONGOING_EVENT|ONLY_ALERT_ONCE|NO_CLEAR|FOREGROUND_SERVICE … actions=1 …) android.title=String (OnionWire is reachable) android.text=String (Tor and the outbox are running so peers can reach wd2zaqo3ge…) NotificationChannel{mId='keep-alive', mName=Node keep-alive, mImportance=2, … mShowBadge=false …} ``` Backgrounding (HOME, 70 s, then re-checked): ``` isForeground=true foregroundId=1 types=0x40000000 … u0_a209 5578 … com.siriusdevops.onionwire.debug # same pid, not killed ``` Doze (`input keyevent 26` + `dumpsys deviceidle force-idle`, 3 minutes): ``` mScreenOn=false mState=IDLE mLightState=OVERRIDE --- after 3 min: mState=IDLE isForeground=true foregroundId=1 types=0x40000000 … u0_a209 5578 … com.siriusdevops.onionwire.debug notification records for channel=keep-alive: 1 $ dumpsys deviceidle unforce Light state: ACTIVE, deep state: ACTIVE ``` and on wake, relaunching the app showed the **same** onion, i.e. the node was never torn down and re-bootstrapped. The notification action, tapped in the shade (expanded notification showed `OnionWire is reachable` / `Tor and the outbox are running so peers can reach wd2zaqo3ge…` / `[Stop keep-alive]` at `bounds=[147,1329][460,1455]`): ``` $ adb shell input tap 303 1392 --- service records remaining: 0 --- notification records: 0 --- process: 1 ``` and the roster then read `Reachable only while this app is open.` — the node stayed up under the UI anchor, exactly as the policy says. Pressing **Lock** in the app bar afterwards returned to the unlock screen with the service gone and nothing in `logcat` but the usual frames. Denied-permission path, observed for real: with `POST_NOTIFICATIONS` still at its default (fresh install), the unlock started the service and `dumpsys activity services` reported `isForeground=true` while the shade had **no** OnionWire notification — the documented "Task Manager, not the drawer" behaviour, not a crash. `android:exported="false"` on the service holds: `adb shell am start-foreground-service -n …KeepAliveService -a …STOP` is refused with `Error: Requires permission not exported from uid 10209`. ### Not verified - **Reachability from a peer while backgrounded.** I confirmed the node, the process and the notification survive backgrounding and forced deep Doze, but I had no second OnionWire peer dialling `wd2zaqo3…` while the screen was off, so "the descriptor stays reachable under Doze" is an inference from "the node was never torn down", not a measured fetch. - **The ViewModel adopt path on a device.** It is covered by the policy unit test (`re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it`), but I could not get the emulator to destroy the activity while keeping the process alive (`always_finish_activities=1` did not destroy it in practice), so the VM-level adoption was not exercised live. - **Long-duration Doze.** 3 minutes, not a 6-hour overnight idle, and the emulator reports `mCharging=true` (Doze was forced, not earned). I would not claim a battery number from this. - No OEM device: Xiaomi/Huawei/Samsung battery managers kill more than AOSP Doze does, and nothing here has been run against one. ## Files touched ``` android/app/src/main/AndroidManifest.xml | 42 +++- android/app/src/main/java/.../MainActivity.kt | 28 ++- android/app/src/main/java/.../WireViewModel.kt | 222 ++++++----- android/app/src/main/java/.../keepalive/KeepAliveService.kt | 181 ++++++++++ android/app/src/main/java/.../keepalive/NodeHost.kt | 153 +++++++++ android/app/src/main/java/.../keepalive/NodeLifetime.kt | 99 ++++++ android/app/src/main/java/.../ui/RosterScreen.kt | 9 + android/app/src/main/java/.../ui/UnlockScreen.kt | 4 +- android/app/src/main/res/drawable/ic_stat_onion.xml | 17 ++ android/app/src/main/res/values/strings.xml | 16 + android/app/src/test/java/.../keepalive/NodeLifetimeTest.kt | 130 +++++++++ 11 files changed, 814 insertions(+), 87 deletions(-) ``` `README.md` untouched (owned by #38); `src/**`, `crates/**`, `.forgejo/workflows/**` untouched. `crates/onionwire-sdk/Cargo.lock` is rewritten by any `cargo ndk` build in the tree and was reverted before committing — it is out of scope here. ## README (deferred) No change needed: `README.md` on this base makes no claim about background lifetime or about INTERNET being the only permission, so nothing in it is now false. The two stale statements were the app manifest comment and the unlock screen's "INTERNET is the only permission this app requests." line; both are fixed in this PR. If you want the keep-alive documented in README at all, the one sentence I would add under the Android section is: > On unlock the app starts a foreground service with an ongoing notification (`specialUse`) so > peers can still reach your onion while the screen is off; **Lock**, or the notification's > **Stop keep-alive** action, ends it.
WireViewModel owned the single Wire node and called shutdown() from
onCleared(), so a backgrounded node died with the UI. Node lifetime is now
arbitrated by a pure policy (NodeLifetime) with two anchors — UI and
keep-alive — and one process-wide owner (NodeHost) that is the only caller
of flush()/shutdown() in the app.

KeepAliveService holds the process in the foreground behind an ongoing
notification from the "keep-alive" channel, started on unlock and stopped
by Lock or the notification action, so peers can still reach the device
while the screen is off.

- foregroundServiceType="specialUse": dataSync is documented as a finite
  transfer (upload/download/backup) and this is an always-on node
- POST_NOTIFICATIONS requested when the node becomes reachable; denial
  keeps the service running with no visible notice instead of failing
- re-unlock with a node the service kept alive adopts it rather than
  reopening the store the live node still holds
- 9 device-free unit tests for the start/stop/re-unlock state machine
Author
Owner

CI on this PR: none, by design

.forgejo/workflows/ci.yml path-filters to src/**, crates/**, tests/**, Cargo.toml, Cargo.lock — this PR touches only android/**, so no check will ever appear for it. The android build is covered by android-release.yml on main, not here.

If you want a real CI signal on this branch before #49 lands, dispatch it manually (workflow_dispatch has no path filter):

POST /api/v1/repos/sirius/onionwire/actions/workflows/ci.yml/dispatches {"ref":"feat/android-foreground-keepalive"}

Local evidence for exactly this tree is in the PR body: :app:assembleDebug + :app:testDebugUnitTest green (34 tests / 0 failures) on arm64-v8a, plus the API 35 emulator dumpsys showing isForeground=true types=0x40000000 through backgrounding and forced deep Doze.

## CI on this PR: none, by design `.forgejo/workflows/ci.yml` path-filters to `src/**`, `crates/**`, `tests/**`, `Cargo.toml`, `Cargo.lock` — this PR touches only `android/**`, so **no check will ever appear for it**. The android build is covered by `android-release.yml` on `main`, not here. If you want a real CI signal on this branch before #49 lands, dispatch it manually (`workflow_dispatch` has no path filter): ``` POST /api/v1/repos/sirius/onionwire/actions/workflows/ci.yml/dispatches {"ref":"feat/android-foreground-keepalive"} ``` Local evidence for exactly this tree is in the PR body: `:app:assembleDebug` + `:app:testDebugUnitTest` green (34 tests / 0 failures) on arm64-v8a, plus the API 35 emulator `dumpsys` showing `isForeground=true types=0x40000000` through backgrounding and forced deep Doze.
sirius changed target branch from feat/tor-lifecycle to main 2026-09-12 21:18:26 +00:00
sirius merged commit c55dfd2492 into main 2026-09-12 22:08:46 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sirius/onionwire!60
No description provided.