Mobile development
The Android companion lives in mobile/. This page covers its projects, how to build and test it, the platform pitfalls that pass the build silently, and the behaviour a change to the app has to keep. What the app does is described in the mobile reference.
Projects
| Project | Contents | Testable |
|---|---|---|
Reeve.Mobile.Core |
Every view model, service and projection. References no MAUI assembly. | Yes, it is the only unit-test subject |
Reeve.Mobile |
The Android head: XAML, platform services, OS surfaces, the manifest. | Only by building it and running it on a device |
Reeve.Mobile.Tests |
Plain .NET tests of Core. They cannot construct a page, host, activity or container. | |
Reeve.Mobile.UiTests |
Device-driven automation against a built app. | |
Reeve.MatterAndroid.Bindings |
Bindings for the platform commissioner used during pairing. |
Put every decision in Core. Whatever stays in the head can be checked only on a screen.
Build and test
dotnet build mobile/Reeve.Mobile/Reeve.Mobile.csproj -f net11.0-android
dotnet test mobile/Reeve.Mobile.Tests
Reeve.slnx references the Core and test projects. The Android head is not in the solution, so build it explicitly as above. Mobile builds need JDK 21 in JAVA_HOME.
Tests use xUnit, FluentAssertions and hand-written fakes (the shared ones are in mobile/Reeve.Mobile.Tests/TestDoubles.cs, plus FakeTimeProvider for time). There is no mocking library.
CI does not build the Android head. The release workflow builds the signed Release APK on a version tag (vX.Y.Z or vX.Y.Z-rc.N) and attaches it to the GitHub Release. The tag sets the app version and the workflow run number is the Android versionCode. A local build has no release signature, because the release keystore is a repository secret. A green CI run says nothing about the head. Build it locally in Release configuration and run it on a device or emulator, uninstalling the previous build first.
On-device UI tests
mobile/Reeve.Mobile.UiTests drives the app through Appium and UiAutomator2. Without a device, an Appium server and an APK, every test skips with a reason naming what is missing, so dotnet test on a machine with nothing attached passes. The project's README has the full runbook. The rules that matter:
- Test a Release APK, such as the one attached to a GitHub Release. A Debug build does not compile XAML, and Release trimming can remove XAML type converters, so only a trimmed build shows what ships.
- Sign in with a purpose-made account, not the bootstrap admin, whose forced password change on first use would invalidate the credential for the next run.
- A physical phone cannot reach the emulator's default host address. The harness runs
adb reverseso the phone reaches the host over the channel it is driven by. - A session against a locked phone is created and then fails every lookup with
NoSuchElementException, so the fixture refuses to start. - MAUI maps
AutomationIdto Android'sresource-id, not to the content description. Locate elements withMobileBy.Id, notAccessibilityId. - A tap test asserts the resulting selection, not only that the click landed. Measure touch targets from rendered bounds. A screenshot is authoritative for anything visual.
- Let the screen settle before reading the hierarchy. A stale dump looks like a broken feature.
Platform pitfalls
Each of these builds cleanly and logs nothing, so check them by hand.
Build and trimming
- Check markup in a Release build. A Debug build does not compile XAML, so invalid markup ships.
- Declare a typed resource for any typed XAML value (a path string bound to a geometry property). Release trimming removes the framework type converters, so a plain string renders empty in Release.
- No managed trim configuration is set. Do not rely on reflection over app type names without pinning the trim mode.
- Keep package versions in the central package-management file only.
- A required platform capability is a required constructor parameter. An optional trailing parameter with no DI registration binds null and drops the feature.
Markup and resources
- Remove a property that no longer exists instead of leaving it in XAML. It compiles and throws when the page loads.
- Declare
x:DataTypeon everyDataTemplate. Without it bindings compile against the outer scope's type and the row renders blank. - Root-anchor a resource-dictionary source path. It is resolved at runtime relative to the referencing file, so a page in a subfolder throws on load.
- Apply
AppThemeBindingat the consumer. A keyed theme-binding colour resource fails to construct and the app cannot launch. - Use tintable vector geometries in a resource dictionary for icons, tinted at the consumer. Do not use an icon font. Show state by tint only, never by swapping the glyph.
- Remove a collapsed collection-view header. It still reserves its height.
- Give a 48 dp tap area a transparent background (
BackgroundColor="Transparent"). A view with no background is not hit-testable. - Keep the Devices tab
CollectionViewvirtualised. Do not wrap it in aScrollView. - Draw an edge fade as a
Shapewith a gradientFillandInputTransparent="True".
Manifest and OS surfaces
- Nothing validates permission strings or manifest attribute names. A typo compiles and silently disables the surface, and a bind permission the platform does not define makes the system list zero candidate services. Confirm a permission exists on a real image before adding it.
- Keep both sides equal for a component declared by an attribute and in the hand-written manifest. The manifest merger unions them and does not reconcile.
- To debug a dead OS surface, dump the built app's compiled resource XML, check the permission is real, then check what the system accepted and what the package manager sees. If the package manager finds the service and the system reports zero, the permission filter is the cause.
- The baby monitor needs
SCHEDULE_EXACT_ALARMwithmaxSdkVersion="32"next toUSE_EXACT_ALARM, becauseUSE_EXACT_ALARMexists only from API 33. - Resolve the live host page explicitly. After an activity re-creation (a font-scale or locale change too), window index zero is the dying window for about a second.
- Keep the main activity single-top and give it an explicit class name. Without single-top a plain start discards the intent or pushes a second activity, and pinned shortcuts store the component name.
- Rehydrate the session before an external surface (widget, shortcut, controls panel, tile, notification receiver) decides the user is signed out. These start in a cold process with no activity. Latch a session probe only on an authoritative outcome (a real HTTP status or an explicit login or sign-out), never on a cancelled wait, an offline failure or a deadline.
- Do not export a widget's remote-views service. The system binds it while holding the bind permission, and exporting it gives a silently empty grid.
- Leave a widget's periodic-update attribute at zero and drive refresh from the scheduler. The attribute has a 30-minute floor.
- Verify the controls panel's confirmation dialog in the device command log, not on screen. Check that the dialog dispatches the chosen value and that declining dispatches nothing.
- The app's WebView handler repeats the stock MAUI WebView setup and adds the touch claim. After a MAUI upgrade, compare it with the framework's handler.
Location and networking
- Start a foreground service while the app is visible, never from the background. A
location-typed service is checked against runtime permissions at start, so a revoked permission throws on the main thread. Drop the location job instead. - Declare both coarse and fine location. The framework's permission wrapper throws when coarse is missing. Request fine location first, then background location as a separate request that opens a system settings page.
- Do not read a missing speed on a GPS fix as standing still. The fused provider omits speed on nearly every fix.
- The app refuses cleartext HTTP, including embedded web views. Use HTTPS.
- Seed the platform cookie manager explicitly for an embedded web view, which has its own cookie jar. Build embed URLs by appending to the configured base so a server under a path prefix is not rewritten to the root.
- The camera embed keeps its zoom in the embedded page and enables it only while the picture is full screen. The picture sits in the touch-claiming web view, or the scroll view above it cancels the pinch.
- Test a client response type against a real backend when it changes. A deserialised response fills missing members with defaults, so a drifted type yields blank labels or a login that succeeds and stays on the sign-in screen. Mock-based tests cannot catch it.
Accessibility and verification
- Use
MinimumHeightRequest, neverHeightRequest, so rows grow with the system font scale up to 200 %. Do not switch off font auto-scaling app-wide. - Make every interactive target at least 48 by 48 dp. The visual may be smaller.
- Give a rotary control explicit minus and plus buttons. Give chips and drag targets semantic descriptions and an activatable role.
- Uninstall the previous build before installing a new one. Installing over it causes intermittent rendering faults.
- Re-test on a device for each commit that changes the head.
- When something breaks only in Release, isolate it by changing one declaration at a time.
Behaviour to keep
A change to the app keeps the behaviour described here.
Camera pictures
- Camera tiles and baby-monitor rooms show a placeholder and request no picture until the user opens the device drawer, or taps the tile when the "load pictures automatically" setting is on (off by default). A snapshot dials the camera and wakes a battery or cloud camera.
- The only camera call on page load is the list of media transports.
- Never fetch a picture withheld for privacy. Drop remembered stills on a privacy change and on sign-out. The server does not gate snapshots on privacy, so the client does.
- The live preview is an embedded page in a WebView. Copy the session into the WebView cookie jar with
Secureonly for https, because on http the cookie manager silently drops a Secure cookie.
Session and sign-out
Authentication is a cookie session. The app keeps no bearer token and does no refresh or expiry tracking.
- A cold start loads the persisted cookie and validates it with
GET /api/auth/me. Only a 401 proves the cookie dead and purges it. Offline, a timeout, a captive portal or a 5xx fail closed to the login screen without clearing the cookie. - Never save a malformed base URL.
- Sign-out also removes the cookie copy in the WebView jar.
Several Android surfaces outlive the session on a shared phone, so sign-out scrubs them. The scrub runs only for a proven teardown (a logout, a background 401, or a cold-start probe with a real HTTP status), never for "no session resolved right now". It clears pinned and dynamic shortcuts, home-screen widget plates, Device Controls placeholders and Quick Settings tiles, the system clipboard (only when the clip carries the app's own label), the in-memory two-factor and recovery-code carriers, the location reporter's retry queue, the favourites state and, last, the on-disk offline cache.
Sign-in restores only what latched: shortcuts that resolve against devices the new user can see, a widget repaint and a Device Controls reload. Give anything that touches the network at sign-in its own time bound, because the HttpClient default timeout is 130 seconds.
Second factor, step-up and recovery codes
- Create the second-factor challenge verifier with a cryptographic RNG, encode it as unpadded base64url like the web and backend, and do it before the login request. The server derives the SHA-256 commitment. Never accept a verifier from a URL, intent or deep link.
- Step-up tokens are single use and bound to a purpose. Write the purpose wire spellings explicitly, not with
ToString(). - Ask only for factors the server offers. Refuse before sending a blank code, a password for an account that holds a second factor, or a code for a password-only account.
- Pass passkey options and assertion JSON verbatim. Passkey outcomes are a closed vocabulary with copy written in Core. Never show server prose.
- Recovery and backup codes exist in plaintext in one response only. Keep them in memory, erase them after verification, and always offer "Later" on the low-backup-codes screen.
- Take a biometric prompt's outcome from the platform's error code. Only the two lockouts count as a denial. A prompt the system ended is an interruption that offers Unlock, because the failure path signs the user out.
Device Controls panel
Core decides everything and the head only maps descriptors.
- Controls are per channel with id
{deviceId}:ch{N}, or a bare GUID for a device with no channels. The channel index is what the descriptor declares, never a list position. A channel whose number cannot be resolved gets no tile and no command. - Lock-screen operation is an allowlist of canonical types. A cover qualifies only when it declares a safe class (blinds). An absent or unrecognised class (garage) requires authentication. A critical flag overrides the allowlist, and an unreadable flag counts as critical.
- A lock's ON position is the secured position, so a "turn on" never unlocks. An unknown lock state never reads as ON.
Quick Settings scene tiles
There are three scene slots (one tile per manifest-declared component), numbered from 1 and mapped to scenes in a persisted mapping.
- The first tap arms the slot for a bounded window. The second tap runs the scene.
- A tile that cannot act (signed out, preference off, slot unmapped, scene missing from the server-filtered runnable list) sends the tap to Settings.
- Tile labels carry scene names and survive process death, so wipe the mapping when a different user signs in, not on sign-out. When the user cannot be read, wipe nothing and refuse to act.
Launcher shortcuts
- A shortcut id is the control id (
{guid}:ch{N}, or a bare GUID without a channel), so a shortcut, a system control and the device sheet name the same channel and republishing updates in place. - Sign-out neutralises every pinned copy: rewrite both labels, strip the deep-link extras, then disable the shortcut. Guard each platform call separately so a refusal never skips the disable.
Home-screen widgets
- The periodic worker re-renders every 15 minutes, as a floor under push-driven updates. Coalesce pushes trailing-edge and take time from a monotonic clock.
- Widgets are display-only. A cached value keeps its fill and is desaturated. "On" never renders as empty. Timestamps read "as of HH:mm", never "since".
Device stream, background delivery and location
- The device hub reconnect schedule never gives up (the SignalR default stops after about 30 seconds). Rebuild a connection by state, because one whose negotiation threw stays non-null but disconnected.
- The server mutes the device stream while the app is hidden and unheld, and the client retries unmuting on a timer. Automation notifications arrive either way. After a mute, reconnect or restart, raise "frames may have been missed" so screens reload, but not for the process's first connection.
- "Notify me when the app is closed" is opt-in and off by default. The hub stays up in the background only when the preference reads true or a baby-monitor session is live. An unreadable preference hangs up.
- Location sharing consent defaults on, and the GPS loop and foreground service start and stop with it. Polling slows when the battery is low or the phone is not moving.
Device sheets
Device sheets mirror the web rules and share projections with the tiles, so the two cannot disagree.
- A capability that has not reported shows a dash, never off or zero.
- A number row uses the descriptor's domain. Without one it uses a unit-based fallback for known units only, and otherwise free numeric entry. Widen the range to include the current reading.
- A realtime frame with a null canonical projection or descriptor means "this frame does not say", never "cleared". When canonical state is present it replaces the old state wholesale. A read older than the cached capture changes nothing.
- A critical capability is actuated only by a discrete confirmed action. The first press arms "Confirm?" for 4 seconds on the capability and exact value, and the confirming press must match both. Drags never actuate until release.
- The camera PTZ pad sends pan and tilt as one canonical command, aims inside the descriptor's domain, and offers a centre only if both axes declare a domain. Rising tilt aims the lens up.
- Numeric entry is text, because MAUI formats with the current culture and parses invariant, so "1,5" would become 15.
Shell, deep links and async-void safety
- The tab host reparents each page's content, so a page's
OnAppearingnever fires. Load a tab through its view model's initialise command, which the host runs on each activation. A tab counts as initialised only when the load ran, and resets on sign-out. - Code invoked from async-void handlers or discarded tasks must never throw, because an escape crashes the app. View models degrade to a status message and observe abandoned parallel tasks.
OnAppearingfires on every return from the app switcher. Latch initialisation, keep reads safe to repeat and keep on-screen state. Every load catches, because an uncaught non-2xx or JSON error ends the process.- Complete the auth gate before any deep link reads authentication state and always release it in a
finally. Admit an external open request (widget, shortcut, Device Controls, notification) once, for the intent that carried it. Drop it when stale and do not replay it on a restored or Recents delivery. Keep intent-extra keys in one place and keep the staticshortcuts.xmlin step with them. - The app lock has one owner, the host page that shows the cover. It starts locked, and only an answered unlock or a session end opens it. Drive the AndroidX
BiometricPromptdirectly, becausePlugin.Fingerprintfolds nearly every error code into one failure. Start it after the window is activated and a dispatcher turn, becauseauthenticatecalled beforeonStartis dropped without a callback.
View-model rules
- A capability a feature cannot work without is a required constructor parameter. An optional trailing one exists only where tests must build the type without it, and null then degrades to a documented no-op.
- CommunityToolkit
ExecuteAsyncignoresCanExecute. Give every async command that must not run twice (verify enrolment, disable 2FA, regenerate codes, begin enrolment) its own re-entrancy guard. - Sort failures into three buckets: the server answered, the request never reached the server, and an
HttpClienttimeout. After a timeout the outcome is unknown, so the copy says only that the request did not get through. Contract drift and anything unforeseen get a fixed sentence. - Never show an exception's own text in the UI. It can embed the
otpauth://URI and secret, a database-shaped token or an internal host. - Run fire-and-forget work through a wrapper that swallows and logs. A throwing background task ends the process.
Permissions and newer servers
- Branch on the permission constants in Core, never on a role name, because roles are configurable. The server stays the gate; the client only chooses which request to attempt. Some permissions imply others on the server, so a branch on one must accept the other (
locations.viewandhome.manage, scenes). - An unknown permission set fails closed for the ecosystems entry.
- Read closed server vocabularies tolerantly so an installed app survives a server that adds values:
- unknown scene skip reasons read as a generic "skipped"
- unknown onboarding states are terminal and not retryable, since the device may already have joined
- unknown commissioning window kinds get no countdown timer
- unknown baby-monitor alarm reasons alarm
- an unrecognised device type is hidden, and infrastructure types are hidden in both modes
- a capability or state entry of a kind the build does not know is left out of device list, detail and hub frames. An unknown basic-tile visibility reads as
auto
Matter onboarding on the phone
The phone's OS commissioner does the pairing. The server runs the provider and correlates the device sync.
- The wizard's step comes from real state: the session poll plus the handler's own phase reports. A stop is offered only while nothing is committed. Once the device has joined the fabric, no outcome may retry.
- The passcode is a secret. It lives only in secure storage and locals and is never logged (only its length). Never log or keep the Thread operational dataset.
- After the commissioner returns, one durable hold in secure storage records the commissioned device so a process death during the relay can be recovered. A storage fault degrades but never abandons the onboarding. A new onboarding waits for the previous hold and refuses to proceed if it could not be cleared.
- Release a hold only when the server answered with something that can never change (unrecoverable statuses, excluding 403). A hold is bounded by age and attempt count and belongs to the user who created it. Do not relay under another user.
Ecosystems wizard (Matter bridge)
The phone only shows a pairing code. It reads the bridge status and explicitly opens a window.
- Opening revokes a live window and creates a new code, so make it reachable only from an explicit tap, never from navigation, appearance or resume. Code reissue and ecosystem removal stay in the web admin.
- An unreadable result is unknown, never "no". After an unknown open the wizard must not say nothing changed, because a window may exist, and it offers only a read, never a second open.
Baby monitor sessions
- A lost link is a status, never a ring. A loss problem chimes once per problem episode, and a heard ring episode is persisted so a kill before the write repeats the ring on the next start.
- Arm the dead-man alarm ahead of time with an interval that exceeds the link-loss bound. A background 401 looks like a sign-out, so only an explicit sign-out ends sessions.
- The two alarm sounds,
baby_monitor_chime.wavandbaby_monitor_pulse.wav, are generated bymobile/tools/generate-baby-monitor-sounds.py.
Favourites, view mode and preferences
- The favourites PUT is a full replacement with no concurrency token, so writes go through a client-side single flight. Read the read-modify-write base only while the gate is held and adopt the server's reply as it is.
AppliedAsRequestedis false when the server's accessibility filter dropped the change. Use that signal, never a 409 or 412.- Edit favourite membership on the device's own card, never from the Home screen.
- Read the view mode from the server preferences, the only place it is stored, once per refresh. It is Basic until a read succeeds, and an offline or forbidden read keeps the last known mode.
Native sign-in and app identity
- The native OIDC callback constant equals the backend default; a test asserts it.
- The official Android app identity (package name and release-certificate SHA-256) is written in the frontend
assetlinks.json, and a test checks the backend copy for drift. Never derive it from a debug-signed APK. - Check the sign-in pages in a Release build on a device: the provider row uses a reflective binding that trimming can break.