Skip to content

feat(android): add a pairing manager built on bond state - #127

Merged
framinosona merged 1 commit into
mainfrom
framinosona/android-pairing-manager
Nov 23, 2026
Merged

framinosona merged 1 commit into
mainfrom
framinosona/android-pairing-manager

Conversation

@framinosona

@framinosona framinosona commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds AndroidBluetoothPairingManager, the Android implementation of IBluetoothPairingManager, and exposes it as AndroidBluetoothAdapter.PairingManager. It pairs with BluetoothDevice.CreateBond(), unpairs with removeBond(), 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

BaseBluetoothPairingManager and IBluetoothPairingManager exist, but no platform implements them, so a caller on Android cannot bond with or unbond from a device through the library.

Change Type

  • Feature
  • Bug fix
  • Refactor (refa)
  • Docs only
  • CI/build/tooling

Affected Areas

  • Abstractions
  • Core
  • Platform: Android
  • Platform: iOS/macOS
  • Platform: Windows
  • Platform: DotNetCore fallback
  • Facade (Bluetooth.Maui)
  • Documentation

Behavior And Compatibility

  • Public API changed
  • Exception behavior changed
  • DI registration behavior changed
  • Capability matrix impact
  • No externally visible behavior change

New public type AndroidBluetoothPairingManager and new property AndroidBluetoothAdapter.PairingManager, both with XML docs. Nothing existing changes. No platform registers IBluetoothPairingManager in DI today and this PR does not add a registration; the manager is reached through the adapter property.

Platform Notes

  • Bonds belong to the Android Bluetooth stack: a bond made here is visible to every app and survives disconnections and app restarts.
  • 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 as BondingFailedException (with the Java exception as inner exception) and the pending operation is cleared; it does not escape as a raw Java exception.
  • The bond state broadcast is registered when the first operation starts (exported on Android 13 and later, which is safe for a protected system broadcast). The bond state is also polled every 250 ms for up to 60 s while an operation is pending, in case the broadcast does not arrive.
  • Default timeouts when the caller passes none: 30 s to pair, 10 s to unpair.
  • One operation is tracked at a time. The base class merges concurrent PairAsync calls, so a second pair never reaches the native layer. A pair started while an unpair is still awaited (or the reverse) fails with BondingFailedException and 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

  • Unit tests added/updated
  • Integration/smoke tests added/updated
  • Manual platform validation performed
  • Not applicable (explain)

Validation notes: the repo has no test projects and CI runs no test step. The class is built on BluetoothDevice, BroadcastReceiver and Intent, 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.Droid builds in Release with --no-incremental, 0 warnings and 0 errors. Pairing, unpairing, the pair/unpair collision, the late-result path and the blocked removeBond path have not been run.

Documentation

  • Docs updated in same PR
  • Capability claims verified against implementation
  • Links validated
  • Not applicable (explain): no document lists Android pairing support; the new public members carry XML docs.

Logging / Diagnostics

  • New logs added
  • EventId range validated
  • No logging changes

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:

  • Low
  • Medium
  • High

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.PairingManager is first read.

Known limitations or deferred follow-ups:

Checklist

  • I reviewed Docs/Best-Practices/Contribution-DoD.md
  • Commit header follows type (scope): short imperative and is <= 72 chars
  • Commit type is one of: feat, fix, refa, perf, docs, ci, chore, test, build
  • Commit body is 1-2 factual sentences (what/why), no emojis, refs, or co-authors
  • If architectural behavior changed, an ADR was added or updated under Docs/Architecture/ADR

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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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
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 reflected removeBond().
  • 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)))
@framinosona
framinosona merged commit 53f067a into main Nov 23, 2026
10 checks passed
@framinosona
framinosona deleted the framinosona/android-pairing-manager branch November 23, 2026 00:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants