Synchronizing a Google Pixel Watch With an iPhone
iOS gives Wear OS no companion protocol and no Google Mobile Services, but it leaves Bluetooth LE and ANCS open. A Pixel Watch 4 can push steps, distance, heart rate, resting heart rate and sleep into Apple Health over one encrypted link, and receive every iPhone notification and call back. Two measurements rewrote the design. The heart rate sensor was held open around the clock and cost half the battery. And Health Services publishes one interval point per step, which meant two writers for the same figure and the same steps counted twice.

On this page
Audio edition
0:00 / 28:31
Ready
A Pixel Watch paired to an iPhone is usually described as impossible, and the description is accurate about the official route. The Wear OS companion app needs Google Mobile Services, which iOS does not have. The Wear data layer runs over Bluetooth Classic RFCOMM. iOS exposes that to no accessory outside the MFi program. Neither gap is one an application can close.
What iOS does leave open is Bluetooth Low Energy, in both directions. An iOS app can act as a GATT central and talk to whatever peripheral it likes. iOS itself publishes the Apple Notification Center Service to any bonded device that asks. Those two facts are enough for a bridge carrying the parts of the pairing most people use. Steps, distance, floors, heart rate, resting heart rate and last night’s sleep arrive in Apple Health. Every iPhone notification and incoming call arrives on the wrist.
This describes how that bridge is built and the design decision that makes it survive a flaky radio. It covers the HealthKit behavior that broke it for a day. It then covers the measurement showing that the repair for that behavior was itself the bug. One sensor registration halved the watch’s battery life while every document in the repository said the bridge was free. The last section is the parts that remain out of reach. The code is dream-fit , a Wear OS service in Kotlin and an iOS app in SwiftUI.

The shape of the bridge
The watch runs a foreground service publishing a small GATT service, shaped like a Nordic UART. One characteristic the phone writes to, one the phone subscribes to for notifications. Both directions carry newline delimited JSON, chunked to the negotiated MTU minus three bytes.
The iPhone app is the central. It scans for the service, connects, discovers the characteristics, subscribes, and from then on receives messages as they are pushed. The watch advertises in thirty second bursts every five and a half minutes. It stops entirely while something is subscribed, which matters for battery and is covered further down.
Flow control is not optional in either direction, and getting it wrong is the fastest way to lose messages. The watch sends one notification at a time and waits for onNotificationSent before sending the next. The phone drains its write queue only while canSendWriteWithoutResponse is true and resumes from peripheralIsReady(toSendWriteWithoutResponse:). Both ends reassemble on newline and reset the buffer past four kilobytes. A dropped fragment then costs one message rather than wedging the channel for the session.
One authority per figure
The watch is the sole authority for every daily total. The messages carrying those totals are absolute rather than incremental:
{"t":"day","d":"2026-09-06","steps":435,"rhr":57,"dist":312,"floors":2,"bat":92}
Every push carries the complete figure and the watch’s own calendar date. That makes the message idempotent. A repeat changes nothing, a reconnect changes nothing, and two messages arriving out of order leave the same result as one. A protocol of increments would have to solve exactly once delivery over a link that drops several times a day. It would drift permanently the first time it failed.
On the watch, one source owns the total. Health Services publishes a STEPS_DAILY aggregate covering the interval from the start of the day to now, resetting at local midnight. Nothing second guesses it. It is batched for power and can trail the wearer by minutes. That lag is accepted rather than papered over, for reasons the battery section makes concrete.
Two rules keep a replayed aggregate harmless. Within a day the total may only rise. Health Services replays stale snapshots out of order, so a lower figure is more likely to be an old one than a correction. Across days the aggregate is rejected outright. Each one is stamped with the day its interval ends in, so a snapshot of yesterday delivered at 00:01 cannot be adopted as today’s. That snapshot is a complete day’s total. Without the second rule the first one works against you, freezing the real count until tomorrow.
Distance, floors, resting heart rate and sleep follow from the same source. Calories are the one aggregate the watch publishes and the bridge does not carry. CALORIES_DAILY is documented as “the total number of calories over a day (including both BMR and active calories)”. HealthKit’s activeEnergyBurned means the active figure alone, and there is no honest way to split one into the other. A reading of 698 kcal at nine in the morning is a body at rest. The type was dropped rather than carried across the link to be ignored.
What HealthKit stores, and the first way that went wrong
HealthKit cannot store “the total for today” at all. It stores samples, each with a quantity and a time range, and the day’s total is whatever they sum to. The first design therefore worked by difference. It summed the samples this app had already written for the watch’s date. That sum went against the total the watch reported, and one sample covered the gap.
The sum has to be scoped to this app’s own samples, which is what HKSource.default() selects:
private static func mine(from start: Date, to end: Date) -> NSPredicate {
NSCompoundPredicate(andPredicateWithSubpredicates: [
HKQuery.predicateForSamples(withStart: start, end: end),
HKQuery.predicateForObjects(from: [.default()]),
])
}
Without that second clause the sum would include the iPhone’s own pedometer. The difference would then be computed against steps the watch never counted. The same predicate guards deletion, so a correction can never touch another app’s data.
That difference pass begins by asking HealthKit for the sum. On a date where the app has not yet written a sample, the predicate matches nothing, and HKStatisticsQuery does not return zero. It calls back with an error:
No data available for the specified predicate.
That is HKError.errorNoData, code 11 in the com.apple.healthkit domain. It is easy to miss during development. After the first successful write the date is no longer empty, and every later query succeeds. The empty case is reachable only at a date boundary, or on a device where nothing has been recorded yet.
Three HealthKit failures turn up in normal operation, and they need different responses:
| Error (code) | Cause | Correct response |
|---|---|---|
errorNoData (11) | the predicate matched no samples | treat as a sum of zero and continue |
errorDatabaseInaccessible (6) | the device is locked, so the store is sealed | keep the write queued, retry after unlock |
errorAuthorizationDenied (4) | sharing was refused for that type | stop, and show it in the interface |
The version that shipped treated all three identically:
guard error == nil else {
self.syncing = false
return
}
For a locked device that is right. For an empty date it produces a loop with no exit. The query matches nothing, so it errors, so the pass is abandoned. No sample is written, so the date still matches nothing when the next push arrives. On my own phone that was twelve hours of nothing. The watch counted normally throughout, and the phone’s own screen displayed the count correctly the whole time.
The repair classifies rather than collapses:
private static func isNoData(_ error: Error) -> Bool {
let e = error as NSError
return e.domain == HKError.errorDomain
&& e.code == HKError.Code.errorNoData.rawValue
}
An empty range now resolves to zero. Deletion needs the same treatment, since removing nothing from an empty range is a success.
Two general points come out of that day. An error handler that retries is only correct for errors a retry can fix. Grouping a transient failure with a structural one produces a wait that never ends. And a screen that reads from a cache confirms the cache. The step ring here reads the last record the watch pushed, out of UserDefaults, and never reads HealthKit, so it kept showing the right number throughout.
The difference pass was itself the bug
Two days later Apple Health showed a column of forty seven rows reading one step each. All were stamped within the same minute. A single row of 1,182 steps sat above them. I had been sitting down for the hour between.
The 1,182 was arithmetic working correctly on a false premise. It was the day’s total minus what the app believed it had already written. The forty seven single step rows were the other half of the answer. Finding where they came from took a measurement rather than a reading of the code.
Health Services publishes an interval data point per step. A 47 second walk produced 47 STEPS points of value 1.0, roughly 400 milliseconds apart. Ambient heart rate arrives at a similar rate, 359 readings in one batch spanning 11.5 minutes, which is about 29,000 a day.
That number reframes the whole design. The interval points were introduced to place samples on the minutes they belonged to. Apple Health could then merge them against the iPhone’s own reading of the same walk, rather than adding a second one. They were treated as a placement hint for a count the daily aggregate owned. At one point per step they are not a hint. They are the count, arriving one at a time.
So there were two writers for the same steps. The interval points wrote them where they happened, and the difference pass wrote whatever the daily total said was missing. The two views disagree constantly in flight, because the aggregate is batched and the points are not. Every correction the difference pass made was writing steps the other lane had already placed. A three minute settle window, a per type watermark and a delete and rewrite path had all accumulated around that conflict. Each was a workaround for a problem the design had created.
The repair was deletion. The daily absolute no longer writes to HealthKit at all. It drives the watch bezel, the phone’s tiles and the audit line, and nothing else. One lane writes, and it writes each delivery once over the span it happened in. Roughly two hundred lines came out, including the difference query, the settle timer, the last written watermark and the day rewrite.
Contiguous points are merged before they are queued, up to five minutes. A 97 step walk then reaches Apple Health as two rows rather than 97. One is the walk. The other is the single step taken during the nineteen idle minutes before it, which the five minute ceiling refuses to fold in. Heart rate is filed once a minute, at the median of that minute, carried at the time that particular reading was taken.
Carrying a day with nobody listening
An interval point is the one message on this link that cannot be reconstructed later. Health Services publishes it once and keeps no history, so the watch is the only place it exists. That makes the queue holding it the most load bearing thing in the project, and it was carrying three defects at once.
The first killed the process. The radio confirms and discards on a binder thread while the service queues on the main one, and the queue was an unsynchronised ArrayDeque. Worse, an overflow inside send called back into the queue while drain was still iterating it. The crash log is unambiguous:
java.lang.ArrayIndexOutOfBoundsException: length=1234; index=-1
at kotlin.collections.ArrayDeque.removeLast
at DeltaQueue.returned(DeltaQueue.kt:73)
at GattLink.send(GattLink.kt:163)
at DeltaQueue.drain(DeltaQueue.kt:87)
START_STICKY brought the service back, so nothing on the watch looked wrong. The delta lane simply stopped, and the difference pass carried on alone, which is how a morning of sitting still produced that 1,182 row.
The second made a day’s backlog undeliverable. drain handed the entire queue to the link in one burst. The link chunks each message to the MTU and discards its whole backlog past 512 chunks. A large queue therefore overflowed, returned the batch, and burst again on the next attempt. It could never get through. Delivery now goes out in windows of 64, and confirming one window releases the next. Seeded with 800 messages, the queue emptied in thirteen full windows and a remainder, twelve seconds in total, with nothing returned.
The third was throughput. The queue re-serialised itself into a single preferences string on every message, which is unnoticeable at four entries and quadratic at a day’s worth. It is an append only log now, rewritten only when a window is confirmed.
The cap needed the same correction as everything else here. It held 1,000 entries, documented as roughly a day of movement. At one point per step that is about fifteen minutes of walking.
One writer, and a chain of custody
What came out of those three defects is smaller than what went in, and it holds together on one rule. A measurement is published once, and it is written once, and every hop between those two points either confirms or holds.
Each boundary has exactly one thing to get right. Health Services cannot be re-asked, so the disk write happens before anything else. The radio reports whether its queue emptied cleanly, so a window is either forgotten or returned to the front. Confirmation itself can be lost, so the phone deduplicates rather than acknowledging. HealthKit can refuse, so a refusal keeps the delivery instead of dropping it.
The idempotency key is the part worth dwelling on. It is the kind plus the exact span, and it is unique by construction rather than by agreement. Nothing allocates it, nothing negotiates it, and no acknowledgement travels back. Two devices that have never compared notes will always agree on whether they are looking at the same measurement.
The earlier design had all the same problems and no such rule. It had two writers, a settle timer to stop them colliding, a watermark to remember what one of them had done, and a rewrite path for when they collided anyway. Every one of those pieces was correct in isolation. They existed because the daily absolute was being asked to do a job the interval points were already doing.
Delivery that survives a restart on either side
Confirmation can be lost after the data has landed, so delivery is at least once and the phone makes it idempotent. A delta is identified by its kind and its exact span, unique by construction, and one already written is ignored. No acknowledgement travels back, and none is needed.
That dedupe set is persisted, and it has to be read back the way it was written:
written: defaults.stringArray(forKey: HealthMirror.writtenKey) ?? []
The writer encodes JSON and stores a Data value. stringArray(forKey:) returns nil for a Data value, so the set came back empty on every launch. Within a session the dedupe was perfect. Across a relaunch every resend was written again. That is the exact duplicate the design was built to prevent, produced by two lines that never referred to each other.
Removing the difference pass took away the last thing that could repair a gap, so the phone now keeps what HealthKit refuses. A sealed store is the common case, since HealthKit is locked whenever the phone is, and the watch forgets a delivery the moment the radio confirms it. Draining is serial and stops at the first failure rather than skipping past it, because the usual failure applies equally to the next write.
The watch has the mirror image of that problem. START_STICKY restarts a service whose process died, and does nothing across a reboot. There was no BOOT_COMPLETED receiver, so a restarted watch collected nothing until somebody opened the app by hand. One reboot cost about 1,280 steps, and no later message can recover them: the points were published once, to nobody. The receiver that fixes it is nine lines. The platform allows the foreground start under its own boot exemption:
intent={act=dreamfit.BOOT ...}
infoAllowStartForeground=[... code:BOOT_COMPLETED ... BFGS denied: false]
isForeground=true
That is dumpsys activity services rather than logcat, because this watch’s boot chatter rotates the log within minutes.
One consequence is worth stating plainly. With a single writer, a gap is now permanent. The old design over reported when the lanes disagreed; this one under reports when the belt misses, and nothing repairs it. The watch’s ledger of what the radio confirmed rides along in every day message so the audit can name which half failed. Ours below delivered is a write Health refused. Delivered below the watch’s total is a delivery that never arrived.
Notifications and calls, and the bond that carries them
Health data going one way is half a pairing. The other half is the iPhone’s notifications arriving on the wrist, and that needs no protocol of my own, because iOS already publishes one.
The Apple Notification Center Service is a GATT service the iPhone exposes to any bonded device. A client subscribes to the Notification Source characteristic for events. It then asks the Data Source characteristic for each one’s attributes: the originating app, the title, the subtitle, the message. Category one is an incoming call, and PerformNotificationAction answers or declines it. The watch runs a client for this, resolves the source bundle identifier to a name and an icon, groups by app, and posts to its own tray.
Two limits are structural rather than unfinished work. There is no reply channel in ANCS, so a message can be read on the wrist but not answered from it. Call audio cannot be routed to a non-MFi accessory over HFP. The best achievable is caller identity plus answer and decline, with the audio staying on the phone.
ANCS requires the watch to be paired to the iPhone as a Bluetooth accessory, and that pairing turns out to be worth having for a second reason. The bond it creates is an encrypted, MITM protected LE link. The custom GATT service can simply require it:
BluetoothGattCharacteristic(
UUID.fromString(BridgeGatt.RX),
PROPERTY_WRITE or PROPERTY_WRITE_NO_RESPONSE,
BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM,
)
With that permission, and the matching one on the notification descriptor, the stack refuses every read, write and subscribe until the link is encrypted with the bond keys. Heart rate and step counts never cross the air in the clear. Nothing in radio range can connect and read them. The iOS side needs no code for this at all. Core Bluetooth answers an insufficient authentication error by elevating with the keys it already holds, then retrying.
Whether the bond satisfies MITM rather than plain encryption is checkable on the watch:
adb shell dumpsys bluetooth_manager | grep le_authenticated
le_authenticated:T means the pairing was made with numeric comparison, so the strict permission will be honored. The trade is that the bridge now depends on the pairing. Unpair the watch and the service becomes unreachable rather than falling back to plaintext. Advertising stays unencrypted, since discovery cannot work otherwise. An advertisement carries only a service identifier and the device name.
Keeping the link alive
A bridge that works in the demo and dies overnight is not a bridge. Most of the difficulty is in states the radio can reach that neither side thinks to check.
The instructive one: restarting the watch app tears down its GATT server and rebuilds it with an empty subscriber list, while the LE connection underneath survives. iOS restores a subscription whose characteristic discovery never finished, so notifications keep arriving on a handle the app never learned. The watch believes nobody is listening. The phone believes the link is healthy and holds nothing to write with. Neither renegotiates, and the only manual cure is force quitting the phone app, which builds a fresh CBCentralManager that rediscovers and re-subscribes.
That state existed in the code without a name. One boolean was answering two different questions:
let ready = peripheral?.state == .connected && rxCharacteristic != nil
Writing needs a characteristic handle, so for the send path that is correct. The status row asks whether the watch is connected, which is the first half only. Sharing one value between them is why the screen read “Looking for Pixel Watch” while drawing a live heart rate chart from that same watch.
Splitting the two questions and naming the state between them gives it somewhere to be repaired from:
enum LinkPhase {
case radioDown(CBManagerState)
case searching
case connecting
case resolving // connected, still asking which characteristics exist
case receiving // notifications arrive, no handle to answer on
case ready // full duplex
}
searching and ready are resting states. Everything else is a transition. A transition that does not complete is a fault rather than a delay, so each carries a deadline. Ten seconds to resolve characteristics, sixty seconds in receiving, three attempts before the connection is dropped and rebuilt. Rebuilding is what forces the fresh discovery and subscription write the watch is waiting for.
A second watchdog covers the quieter failure. The watch pushes a day message every fifteen minutes regardless of activity, so twenty minutes of silence is not a quiet watch but a broken link. At twenty minutes the phone sends a sync request, and at twenty five it drops the connection. Liveness is counted in day messages rather than in bytes. Heart rate arrives every five seconds and would otherwise mask a link that can receive but no longer send.
The sensor that cost half the battery
The advertising budget was the part I measured carefully, and it was never the problem. Low power mode at roughly a one second interval. Transmit power near minus twelve dBm, which is room scale. Thirty seconds of advertising in every five and a half minutes, and none at all while subscribed. Duty averaged, that is 0.05 to 0.08 mA, or 0.4 to 0.6 mAh a day. The design cell is 455 mAh at charge_full_design, so the radio costs about a tenth of a percent of it. The repository said so in three places, and every figure in it was right.
The watch was losing half its charge anyway, and the reason was a line nobody had budgeted:
register(Sensor.TYPE_HEART_RATE, "heart rate")
Registered once when the service started, never unregistered. The optical sensor is not a register to read but a light source to power, green LEDs plus the analog front end. It ran for the life of a foreground service designed never to die. One discharge, from dumpsys batterystats:
Sensor 65567 (HeartRate): 21h 21m 33s realtime
Time on battery: 21h 23m 55s
99.8 percent duty. dumpsys sensorservice names the only client holding it:
HeartRate (handle=0x0001001f, connections=1)
com.drmhse.dream.fit.BridgeService | uid 10164
Not Fitbit, not Health Services, not the watch face. The platform’s own sampling goes through the Wear health services HAL, which drops its connection between samples. The one process holding the sensor framework’s handle open around the clock was mine.
The drain profile matches a powered rail rather than running code. Of 417 mAh discharged, 359 mAh went while the device was in deep doze, against 5 minutes 45 seconds of total app CPU time. An A/B measurement of instantaneous current from /sys/class/power_supply/battery/current_now separates the two states. Sampled every five seconds for ninety seconds, screen off. The comparison is by floor rather than median, since both distributions are bimodal with WiFi and system wakeups on top:
| idle floor | 7 lowest samples (mA) | |
|---|---|---|
| service running | 10.19 mA | 10.2, 10.6, 10.8, 13.3, 13.4, 13.6, 15.4 |
| service force stopped | 2.38 mA | 2.4, 2.5, 2.6, 2.7, 2.9, 3.4, 4.0 |
With the service running the watch never reached 10.2 mA across eighteen samples. Force stopped it settled at 2.4 mA within seconds. A continuously held sensor sets a floor the device cannot dip below, however deeply it dozes. That is why the cost is invisible in any profile looking for busy code. Removing it takes the session average from 19.5 mA to about 11.7 mA, which is 23 hours of life against roughly 40.
Two things hid it for as long as they did. The service holds no wakelock, so the check the repository documented reported clean. That check was dumpsys batterystats | grep -i dreamfit. grep on the package name matches the uid mapping line, not the Sensor 65567: line underneath it. The per uid energy model is no help either. It attributed 18.5 mAh to the app while assigning 339 mAh of a 411 mAh total to uid 1000. This device carries no per uid coefficient for the optical sensor, so the hardware cost lands on the system rather than on whoever asked for it. The duration line is measured, the attribution is modelled, and only the measured one was worth anything.
The repair splits the two by cost. Ambient readings come from Health Services passive monitoring, which taps sampling the platform already performs. Live readings come from MeasureClient, which powers the sensor only while registered. It is therefore registered only while somebody is looking: the phone subscribed, the phone just wrote, or the watch screen came up. Each buys a 120 second window. Passive delivery arrives in batches, 112 samples spanning three and a half minutes in one callback. The resting rate needs twelve samples in ten minutes, so that is far more than enough.
The general shape is worth keeping. The document budgeted the component it had decided was expensive. It filed the sensor under existing load, as though holding a rail open were something the platform did anyway. Its verification command then checked for the wrong kind of evidence, which made the absence of a finding feel like a finding.
Sleep, and a watch on a desk
Sleep is the one figure a pocketed phone cannot measure at all. It is therefore the most valuable thing the bridge can carry, and it took two wrong conclusions to reach.
The first was mine: grepping the Health Services DataType list for sleep returns nothing, and I reported it as impossible. Sleep is not a data type. It is a user activity state, delivered through a different callback on the same client. This watch supports it:
caps states=[USER_ACTIVITY_PASSIVE, USER_ACTIVITY_EXERCISE, USER_ACTIVITY_ASLEEP]
PassiveListenerConfig.setShouldUserActivityInfoBeRequested(true) turns on onUserActivityInfoReceived, which carries a state and the instant that state took effect. What it does not carry is any notion of a wrist. That is the second wrong conclusion, and the device volunteered it before any of this reached Apple Health:
off body detect: 1.00 (07:29:12) -> 0.00 (07:34:08)
activity USER_ACTIVITY_ASLEEP at 09:12:30
The watch had been off my wrist for an hour and thirty eight minutes, and Health Services called it sleep. USER_ACTIVITY_ASLEEP means the watch is still, which is a good proxy for a sleeping wearer and a perfect description of a watch on a charger. Writing that to HealthKit would have invented a night every time the watch charged. A fabricated sleep sample is indistinguishable from a real one once it is in the store.
So every session is gated on TYPE_LOW_LATENCY_OFFBODY_DETECT, the only raw sensor left in the app. That exception is worth defending on its own terms. Off body is not something Health Services reports, so it is no second source for a figure already available. It is also an on change, non optical sensor the system already holds several clients on. The app’s registration is therefore shared rather than additional. It is the opposite of the sensor that started this section.
The gate on its own was not enough. A state delivered on registration is dated when it took effect. That is routinely in the past, possibly while the watch was on a desk. A session start is therefore clamped to the moment the wrist actually began. Only an off to on transition observed while running dates the wrist at all, because the value an on change sensor hands over at registration says worn, not since when. Sessions shorter than fifteen minutes are stillness and longer than sixteen hours are a wake transition that was never seen. Taking the watch off closes the session then and there. Removal is the last moment there is evidence for, and a wake time guessed from a bedside table is worse than a night reported short.
Health Services also corrects itself slowly. In the run above the state stayed ASLEEP for thirteen minutes after I put the watch on and was awake. The fifteen minute minimum discarded that by a margin of two. The clamp is what makes that robust rather than lucky.
What is still out of reach
None of what the bridge cannot do is a matter of effort. eSIM provisioning, Google Wallet payments, Play Store installs from the phone and Fitbit cloud synchronization all need the same missing things. Either Google Mobile Services, or carrier and secure element access that neither platform grants a third party. Media control is possible in principle through Apple’s Media Service, which is the same pairing story as ANCS, and is simply not written yet.
Heart rate variability, blood oxygen, skin temperature, respiratory rate and Fitbit’s four stage sleep staging are a different kind of unreachable. Fitbit computes all of them on this watch and files them in Health Connect. Wear OS does not expose Health Connect to applications. getSystemService("healthconnect") returns null on a device whose service list contains healthconnect and whose package list contains the Health Connect controller. The binder service is in the platform image, the client side manager is not registered, and no application on the watch can read any of it. The one route to Fitbit’s staging is its web API from the phone, which trades a local bridge for a cloud account.
The result is not a Pixel phone experience on an iPhone. It is a watch that counts your steps and heart rate into Apple Health, shows your iPhone notifications, and lets you decline a call from your wrist. That is most of what the pairing was for.

