feat(android): foreground service keeps the onion reachable through Doze #60
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/android-foreground-keepalive"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Stacked on #49
Card t_5bf32cd3.
feat/tor-lifecycle(PR #49,Wire.shutdown/flush/torState) is not onmainyet, 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, notmain. Retarget tomainafter #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 akeep-alive is still held returns
Flush, notStop— that is this card in one branch.keepalive/NodeHost.kt— process-wide owner of the singleWire. Only this object callsflush()/shutdown(). The ViewModel and the service both report transitions here.keepalive/KeepAliveService.kt— the foreground service: started on unlock, stopped by Lock orby the notification's action.
WireViewModel— no longer holdswireand no longer callsshutdown().lock()stops theservice first, then asks the policy to tear the node down;
onCleared()reports "UI gone" andlets 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 nolibs.versions.tomlchange:Service,Notification/NotificationChannel/NotificationCompatcome from the platform plusandroidx.core, which is already on the classpath.LifecycleServicewould have bought alifecycleScopethis 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:
One
shutdown(), twoflush(), all three insideNodeHost.WireViewModel.onCleared()used tobe 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.
NodeHostalso moved the SDK's blockingopenWire()ontoDispatchers.IO: on this base it ran insideviewModelScope.launchon the main thread, which isminutes of Tor bootstrap on the main thread.
FGS type:
specialUse, notdataSyncThe card suggested
dataSync. The SDK documentsdataSyncas "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 usecases 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;dataSyncwouldcost a declaration that does not describe the app.
Also rejected:
remoteMessaging(message transfer when switching devices) andconnectedDevice(external accessories; would also drag in
CHANGE_NETWORK_STATE).minSdk 26/targetSdk 36unchanged, soFOREGROUND_SERVICE_SPECIAL_USEis declared next toFOREGROUND_SERVICE.The notification, and what it is allowed to say
Channel
keep-alive,IMPORTANCE_LOW, no sound, no badge, ongoing. Text names the moving partsinstead of saying "running in the background":
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 wouldcome 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 startsand 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. LikewisestartForeground()itself is wrapped: on API 31+ a background start throwsForegroundServiceStartNotAllowedException, which is caught, recorded asKeepAliveStatus.Unavailable, and shown on the roster instead of killing the process.Verified
Build + unit tests (arm64-v8a, the shipped ABI)
app-debug.apk— 46,925,810 bytes, sha2567847b495965b45397082056a6b620e557101ad0e5cc0e024cc8f9dd7c80464c3,packaging
lib/arm64-v8a/libonionwire_sdk.so(34,439,472 bytes).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 buildBuilt
-Ponionwire.abis=x86_64for 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 locatorwd2zaqo3gemlzwmnj3vuhd2k7vfvevlnbpzlfwnvmpwrbdx44xuaklad.onion.Service in the foreground, notification posted:
types=0x40000000isFOREGROUND_SERVICE_TYPE_SPECIAL_USE;startCommandResult=2isSTART_NOT_STICKY. The notification itself:Backgrounding (HOME, 70 s, then re-checked):
Doze (
input keyevent 26+dumpsys deviceidle force-idle, 3 minutes):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]atbounds=[147,1329][460,1455]):and the roster then read
Reachable only while this app is open.— the node stayed up under the UIanchor, exactly as the policy says. Pressing Lock in the app bar afterwards returned to the
unlock screen with the service gone and nothing in
logcatbut the usual frames.Denied-permission path, observed for real: with
POST_NOTIFICATIONSstill at its default(fresh install), the unlock started the service and
dumpsys activity servicesreportedisForeground=truewhile 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 …STOPis refused withError: Requires permission not exported from uid 10209.Not verified
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.
(
re_unlock_while_the_keep_alive_still_holds_the_node_adopts_it), but I could not get theemulator to destroy the activity while keeping the process alive (
always_finish_activities=1did not destroy it in practice), so the VM-level adoption was not exercised live.
mCharging=true(Doze was forced, not earned). I would not claim a battery number from this.here has been run against one.
Files touched
README.mduntouched (owned by #38);src/**,crates/**,.forgejo/workflows/**untouched.crates/onionwire-sdk/Cargo.lockis rewritten by anycargo ndkbuild in the tree and wasreverted before committing — it is out of scope here.
README (deferred)
No change needed:
README.mdon this base makes no claim about background lifetime or aboutINTERNET 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:
CI on this PR: none, by design
.forgejo/workflows/ci.ymlpath-filters tosrc/**,crates/**,tests/**,Cargo.toml,Cargo.lock— this PR touches onlyandroid/**, so no check will ever appear for it. The android build is covered byandroid-release.ymlonmain, not here.If you want a real CI signal on this branch before #49 lands, dispatch it manually (
workflow_dispatchhas no path filter):Local evidence for exactly this tree is in the PR body:
:app:assembleDebug+:app:testDebugUnitTestgreen (34 tests / 0 failures) on arm64-v8a, plus the API 35 emulatordumpsysshowingisForeground=true types=0x40000000through backgrounding and forced deep Doze.