Repository navigation
feat(android): add a pairing manager built on bond state - #127
Merged
Merged
Conversation
AndroidBluetoothPairingManager pairs with CreateBond and unpairs with removeBond, completes the operation from the bond state broadcast and a poll, and is exposed as AndroidBluetoothAdapter.PairingManager. It tracks one operation at a time, and a removeBond call that Android blocks is reported as a BondingFailedException.
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved lifecycle races let stale callbacks and pollers complete replacement requests incorrectly, while already-cancelled requests can still initiate bonding or remove a shared persistent bond.
7 open issues
Pre-cancelled requests still initiate native bond changes · New Stale pollers can deliver bond results to replacement operations · New Late callbacks can complete a replacement operation · New PairingManager initialization can create competing instances · New Successful pairing never updates the base paired-device collection · New Bond-state fast paths bypass opposite-operation collision checks · New Unpair polling stops before observing Bond.None · New
What changed in this PR
Adds Android support for the existing pairing abstraction, exposing bond and unbond operations through AndroidBluetoothAdapter.PairingManager.
Changes:
- Implements pairing with
CreateBond()and unpairing through reflectedremoveBond(). - Uses bond-state broadcasts with polling fallback and default operation timeouts.
- Adds lazy adapter access and structured bond-state logging; DI registration remains unchanged.
The implementation has not been validated on a device or emulator.
| File | Description |
|---|---|
| Bluetooth.Maui.Platforms.Droid/Scanning/AndroidBluetoothPairingManager.cs | Implements Android bond operations, completion tracking, polling, and receiver cleanup. |
| Bluetooth.Maui.Platforms.Droid/Logging/AndroidBluetoothLoggerMessages.cs | Adds structured logging for bond-state transitions. |
| Bluetooth.Maui.Platforms.Droid/AndroidBluetoothAdapter.cs | Exposes a lazily created Android pairing manager. |
Review effort: Balanced
Comment on lines
+59
to
+68
| public override ValueTask<bool> PairAsync(IBluetoothRemoteDevice device, TimeSpan? timeout = null, CancellationToken cancellationToken = default) | ||
| { | ||
| return base.PairAsync(device, timeout ?? DefaultPairTimeout, cancellationToken); | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public override ValueTask UnpairAsync(IBluetoothRemoteDevice device, TimeSpan? timeout = null, CancellationToken cancellationToken = default) | ||
| { | ||
| return base.UnpairAsync(device, timeout ?? DefaultUnpairTimeout, cancellationToken); | ||
| } |
Comment on lines
+173
to
+175
| if (_pendingOperation == PendingOperation.None || !string.Equals(_pendingAddress, address, StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| return; // finished by the broadcast, or replaced by another operation |
Comment on lines
+308
to
+309
| case (PendingOperation.Pair, Bond.Bonded) when IsPairing: | ||
| OnPairSucceeded(device); |
Comment on lines
+53
to
+56
| /// <summary> | ||
| /// Gets the pairing manager used to bond with and unbond from remote devices. | ||
| /// </summary> | ||
| public AndroidBluetoothPairingManager PairingManager => field ??= new AndroidBluetoothPairingManager(this, Logger); |
| /// Bonds are owned by the Android Bluetooth stack, not by the app: a bond made here is visible to every other app | ||
| /// and survives disconnections, reboots of the peripheral and app restarts. | ||
| /// </summary> | ||
| public class AndroidBluetoothPairingManager : BaseBluetoothPairingManager, IDisposable |
Comment on lines
+94
to
+95
| OnPairSucceeded(device); | ||
| return ValueTask.CompletedTask; |
|
|
||
| var state = nativeDevice.BondState; | ||
| seenBonding |= state == Bond.Bonding; | ||
| if (state == Bond.Bonded || (state == Bond.None && (seenBonding || unpairing))) |
This was referenced Nov 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
Adds
AndroidBluetoothPairingManager, the Android implementation ofIBluetoothPairingManager, and exposes it asAndroidBluetoothAdapter.PairingManager. It pairs withBluetoothDevice.CreateBond(), unpairs withremoveBond(), and completes the operation from the bond state broadcast, with a poll as a backstop.Not validated on a device or an emulator. It compiles; nothing here has been run against a peripheral.
Why
BaseBluetoothPairingManagerandIBluetoothPairingManagerexist, but no platform implements them, so a caller on Android cannot bond with or unbond from a device through the library.Change Type
refa)Affected Areas
Bluetooth.Maui)Behavior And Compatibility
New public type
AndroidBluetoothPairingManagerand new propertyAndroidBluetoothAdapter.PairingManager, both with XML docs. Nothing existing changes. No platform registersIBluetoothPairingManagerin DI today and this PR does not add a registration; the manager is reached through the adapter property.Platform Notes
BluetoothDevice.removeBond()is a hidden API with no public replacement, so it is called by reflection. Newer Android versions may block that. A blocked, missing or throwing call is reported asBondingFailedException(with the Java exception as inner exception) and the pending operation is cleared; it does not escape as a raw Java exception.PairAsynccalls, so a second pair never reaches the native layer. A pair started while an unpair is still awaited (or the reverse) fails withBondingFailedExceptionand leaves the first untouched. An earlier operation whose caller gave up (timeout, cancellation) is replaced, and its late result is dropped instead of being reported as an unexpected operation.Tests
Validation notes: the repo has no test projects and CI runs no test step. The class is built on
BluetoothDevice,BroadcastReceiverandIntent, which need a device to run, and bonding needs a real peripheral (emulators have no BLE), so a unit test would have to fake the whole native layer.Bluetooth.Maui.Platforms.Droidbuilds in Release with--no-incremental, 0 warnings and 0 errors. Pairing, unpairing, the pair/unpair collision, the late-result path and the blockedremoveBondpath have not been run.Documentation
Logging / Diagnostics
One new message,
LogBondStateChanged,EventId = 7012, in the Android 7000-7999 range (the highest existing Android id is 7011; 8000-8999 is documented as the Apple L2CAP range, so it is not used here).Risks And Follow-ups
Risk level:
New code on a path that has never run on a device, and one hidden-API call. Nothing existing is changed, and the manager is only created when
AndroidBluetoothAdapter.PairingManageris first read.Known limitations or deferred follow-ups:
BaseBluetoothPairingManager.PairAsyncmerges concurrent calls whatever the device, so a secondPairAsyncfor another device waits for, and returns, the first device's result. That is existing base class behavior and is not changed here; it is tracked in [BUG] A second PairAsync or UnpairAsync for another device is merged into the first call and returns its result #128.PairingStateChanged.Disposeon the manager unregisters the receiver.IBluetoothPairingManageris not registered in DI by any platform yet.Checklist
type (scope): short imperativeand is <= 72 chars