diff --git a/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs b/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs
index 0db5be8..1d4a607 100644
--- a/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs
+++ b/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs
@@ -5,7 +5,9 @@
using System.Threading.Tasks;
using Android.Bluetooth;
using Android.Bluetooth.LE;
+using Android.Content;
using Android.OS;
+using System.BluetoothLe.BroadcastReceivers;
using System.BluetoothLe.Extensions;
using Trace = System.BluetoothLe.Trace;
@@ -24,18 +26,65 @@ internal Adapter(BluetoothManager bluetoothManager)
_bluetoothManager = bluetoothManager;
_bluetoothAdapter = bluetoothManager?.Adapter;
- // TODO: bonding
- //var bondStatusBroadcastReceiver = new BondStatusBroadcastReceiver();
- //Application.Context.RegisterReceiver(bondStatusBroadcastReceiver,
- // new IntentFilter(BluetoothDevice.ActionBondStateChanged));
+ _api21ScanCallback = new Api21BleScanCallback(this);
- ////forward events from broadcast receiver
- //bondStatusBroadcastReceiver.BondStateChanged += (s, args) =>
- //{
- // //DeviceBondStateChanged(this, args);
- //};
+ RegisterBondStateReceiver();
+ }
- _api21ScanCallback = new Api21BleScanCallback(this);
+ private BondStatusBroadcastReceiver _bondStatusReceiver;
+
+ private void RegisterBondStateReceiver()
+ {
+ // No adapter means no Bluetooth hardware: there will be no bond changes to report.
+ if (_bluetoothAdapter == null)
+ {
+ return;
+ }
+
+ try
+ {
+ var receiver = new BondStatusBroadcastReceiver(this);
+ var filter = new IntentFilter(BluetoothDevice.ActionBondStateChanged);
+
+ // From API 33 a context-registered receiver must say whether other apps may send to it. This one
+ // receives only a protected system broadcast, which is delivered to a non-exported receiver.
+ if (OperatingSystem.IsAndroidVersionAtLeast(33))
+ {
+ Android.App.Application.Context.RegisterReceiver(receiver, filter, ReceiverFlags.NotExported);
+ }
+ else
+ {
+ Android.App.Application.Context.RegisterReceiver(receiver, filter);
+ }
+
+ _bondStatusReceiver = receiver;
+ }
+ catch (Exception ex)
+ {
+ // Bond state changes are an addition to the adapter, not a condition of it working.
+ Trace.Message("Adapter: Registering for bond state changes failed: {0}", ex.Message);
+ }
+ }
+
+ ///
+ /// The device for : the instance this adapter already tracks - connected
+ /// first, then discovered - or a new one when it tracks none.
+ ///
+ internal Device ResolveDevice(BluetoothDevice nativeDevice)
+ {
+ var id = Device.ParseDeviceId(nativeDevice.Address);
+
+ if (TryGetConnectedDevice(id, out var connected))
+ {
+ return connected;
+ }
+
+ if (DiscoveredDevicesRegistry.TryGetValue(id, out var discovered))
+ {
+ return discovered;
+ }
+
+ return new Device(this, nativeDevice, null, 0);
}
protected Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken)
@@ -205,6 +254,23 @@ public IReadOnlyList GetSystemConnectedOrPairedDevices(Guid[] services =
partial void DisposeNative()
{
+ var bondStatusReceiver = _bondStatusReceiver;
+ _bondStatusReceiver = null;
+
+ if (bondStatusReceiver != null)
+ {
+ try
+ {
+ Android.App.Application.Context.UnregisterReceiver(bondStatusReceiver);
+ }
+ catch (Exception ex)
+ {
+ Trace.Message("Adapter: Unregistering the bond state receiver failed: {0}", ex.Message);
+ }
+
+ bondStatusReceiver.Dispose();
+ }
+
try
{
_bluetoothAdapter?.BluetoothLeScanner?.StopScan(_api21ScanCallback);
diff --git a/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs b/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs
index edf5db3..e16f1ed 100644
--- a/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs
+++ b/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs
@@ -96,6 +96,25 @@ public partial class Adapter : IDisposable
///
public event EventHandler ScanFailed;
+ ///
+ /// Raised when the system reports that a device's bond (pairing) state has changed: bonding started,
+ /// the device bonded, or the bond was removed or failed.
+ ///
+ ///
+ ///
+ /// Raised on Android only, on the main thread, for every Bluetooth device the system reports - including
+ /// devices this adapter has not discovered, and changes made outside the app, for example in the system
+ /// Bluetooth settings. The device in the arguments is the instance this adapter already tracks where
+ /// there is one, so its change is also raised through
+ /// . On Android 12 and later the system delivers the change only to
+ /// an app holding the BLUETOOTH_CONNECT permission.
+ ///
+ ///
+ /// Never raised on Apple platforms, which do not expose bonding, or on Windows.
+ ///
+ ///
+ public event EventHandler DeviceBondStateChanged;
+
#endregion
#region Properties
@@ -567,6 +586,18 @@ internal void HandleDisconnectedDevice(bool disconnectRequested, Device device)
}
}
+ ///
+ /// Reports a bond state change for : raises
+ /// for , then .
+ ///
+ internal void HandleBondStateChanged(Device device, DeviceBondState state)
+ {
+ Trace.Message("Adapter: Bond state of {0} changed to {1}", device.NameOrId, state);
+
+ device.RaiseBondStateChanged();
+ Raise(DeviceBondStateChanged, new DeviceBondStateChangedEventArgs(device, state), nameof(DeviceBondStateChanged));
+ }
+
internal void HandleConnectionFail(Device device, string errorMessage)
{
Trace.Message("Failed to connect peripheral {0}: {1}", device.Id, device.NameOrId);
diff --git a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj
index b101dab..2f51be4 100644
--- a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj
+++ b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj
@@ -51,6 +51,11 @@
BluetoothLe dotnet android ios macos maccatalyst windows wpf netstandard tvos
Copyright © 2026 DSoft
+ Unreleased - Device.BondState reports a device's bond (pairing) state, and on Android
+ Adapter.DeviceBondStateChanged is raised when it changes. DeviceBondState gains Unknown, declared last
+ so existing values are unchanged, which Apple platforms always report because CoreBluetooth does not
+ expose bonding. BondStatusBroadcastReceiver is now registered by the Android adapter.
+
4.0.1 - restores the stand-in seam that 4.0 removed. Device and Service can again be derived outside
the library: protected Device(Guid id, string name, int rssi = 0) replaces the parameterless
protected Device() that 3.x exposed, and Service(Device) is protected again. Device.Id stays
diff --git a/DSoft.System.BluetoothLe/Devices/Device.android.cs b/DSoft.System.BluetoothLe/Devices/Device.android.cs
index ace76a4..8ce07e8 100644
--- a/DSoft.System.BluetoothLe/Devices/Device.android.cs
+++ b/DSoft.System.BluetoothLe/Devices/Device.android.cs
@@ -61,10 +61,16 @@ internal Device(Adapter adapter, BluetoothDevice nativeDevice, BluetoothGatt gat
#region Methods
#region Private
- private Guid ParseDeviceId()
+ private Guid ParseDeviceId() => ParseDeviceId(NativeDevice.Address);
+
+ ///
+ /// The id a device with this MAC address is given: the address in the last six bytes of an otherwise
+ /// zero GUID. Shared with the adapter, which has only an address when the system reports a bond change.
+ ///
+ internal static Guid ParseDeviceId(string address)
{
var deviceGuid = new byte[16];
- var macWithoutColons = NativeDevice.Address.Replace(":", "");
+ var macWithoutColons = address.Replace(":", "");
var macBytes = Enumerable.Range(0, macWithoutColons.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(macWithoutColons.Substring(x, 2), 16))
@@ -223,6 +229,34 @@ private DeviceState GetState()
}
}
+ private DeviceBondState GetBondState()
+ {
+ // No native device: a stand-in built through the protected constructor.
+ if (NativeDevice == null)
+ {
+ return DeviceBondState.Unknown;
+ }
+
+ // Throws SecurityException on Android 12 and later without BLUETOOTH_CONNECT; BondState reports
+ // that as Unknown.
+ return ToBondState(NativeDevice.BondState);
+ }
+
+ internal static DeviceBondState ToBondState(Bond bond)
+ {
+ switch (bond)
+ {
+ case Bond.None:
+ return DeviceBondState.NotBonded;
+ case Bond.Bonding:
+ return DeviceBondState.Bonding;
+ case Bond.Bonded:
+ return DeviceBondState.Bonded;
+ default:
+ return DeviceBondState.Unknown;
+ }
+ }
+
private async Task UpdateRssiNativeAsync(CancellationToken cancellationToken)
{
if (_gatt == null || _gattCallback == null)
diff --git a/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs b/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs
index a236f08..6e80e7d 100644
--- a/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs
+++ b/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs
@@ -157,6 +157,10 @@ private Task UpdateRssiNativeAsync(CancellationToken cancellationToken)
token: cancellationToken);
}
+ // CoreBluetooth has no API for the bond state: pairing happens on demand, driven by the OS, the first
+ // time an encrypted characteristic is accessed.
+ private DeviceBondState GetBondState() => DeviceBondState.Unknown;
+
private DeviceState GetState()
{
switch (NativeDevice.State)
diff --git a/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs b/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs
index 88db689..e8c0213 100644
--- a/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs
+++ b/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs
@@ -26,6 +26,9 @@ partial void DisposeNative()
private Task UpdateRssiNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage);
+ // Reported rather than thrown: BondState is documented never to throw.
+ private DeviceBondState GetBondState() => DeviceBondState.Unknown;
+
private DeviceState GetState() => throw new System.PlatformNotSupportedException(NotSupportedMessage);
private Task> GetServicesNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage);
diff --git a/DSoft.System.BluetoothLe/Devices/Device.shared.cs b/DSoft.System.BluetoothLe/Devices/Device.shared.cs
index 609b7d8..2a5233e 100644
--- a/DSoft.System.BluetoothLe/Devices/Device.shared.cs
+++ b/DSoft.System.BluetoothLe/Devices/Device.shared.cs
@@ -91,6 +91,48 @@ public DeviceState State
}
}
+ ///
+ /// Gets the bond (pairing) state of the device, as the platform reports it now.
+ ///
+ ///
+ ///
+ /// Android reads it from the system on every call. Windows reports
+ /// or from the device's pairing information, and never
+ /// . Apple platforms always report
+ /// : CoreBluetooth pairs on demand, the first time an encrypted
+ /// characteristic is accessed, and does not let an app ask whether a bond exists.
+ ///
+ ///
+ /// is also reported where the state cannot be read - on Android 12
+ /// and later without the BLUETOOTH_CONNECT permission, on a target without Bluetooth, for a stand-in
+ /// device, and once the device has been disposed. Reading this property never throws.
+ ///
+ ///
+ /// On Android, reports changes, and
+ /// is raised for this property on the instance the adapter tracks.
+ ///
+ ///
+ public DeviceBondState BondState
+ {
+ get
+ {
+ if (_isDisposed)
+ {
+ return DeviceBondState.Unknown;
+ }
+
+ try
+ {
+ return GetBondState();
+ }
+ catch (Exception ex)
+ {
+ Trace.Message("Device: Reading the bond state of {0} failed: {1}", NameOrId, ex.Message);
+ return DeviceBondState.Unknown;
+ }
+ }
+ }
+
///
/// Gets whether this instance has ever completed a connection.
///
@@ -339,6 +381,12 @@ protected virtual void Dispose(bool disposing)
///
internal void RaiseStateChanged() => NotifyPropertyChanged(nameof(State));
+ ///
+ /// Raises for . The platform announces bond
+ /// changes system-wide, so the adapter has to drive the notification.
+ ///
+ internal void RaiseBondStateChanged() => NotifyPropertyChanged(nameof(BondState));
+
#endregion
#region Private Methods
diff --git a/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs
index 3272d0e..3ff527a 100644
--- a/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs
+++ b/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs
@@ -92,6 +92,19 @@ private async Task> GetServicesNativeAsync(CancellationTo
.ToList();
}
+ // Windows exposes whether the device is paired, but not a pairing in progress.
+ private DeviceBondState GetBondState()
+ {
+ var native = NativeDevice;
+
+ if (native == null)
+ {
+ return DeviceBondState.Unknown;
+ }
+
+ return native.IsPaired ? DeviceBondState.Bonded : DeviceBondState.NotBonded;
+ }
+
private DeviceState GetState()
{
if (NativeDevice.IsConnected)
diff --git a/DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs b/DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs
index bab5f85..723afd2 100644
--- a/DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs
+++ b/DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs
@@ -1,9 +1,26 @@
namespace System.BluetoothLe
{
+ ///
+ /// The bond (pairing) state of a device, as the platform reports it.
+ ///
public enum DeviceBondState
{
+ /// The platform reports that the device is not bonded.
NotBonded,
+
+ /// Bonding with the device is in progress.
Bonding,
- Bonded
+
+ /// The device is bonded: the platform holds keys for an encrypted link to it.
+ Bonded,
+
+ ///
+ /// The platform does not expose the bond state. Apple platforms always report this: CoreBluetooth
+ /// pairs on demand, the first time an encrypted characteristic is accessed, and offers no way to ask
+ /// whether a bond exists. Also reported where the state cannot be read, for example on Android 12 and
+ /// later without the BLUETOOTH_CONNECT permission, and for a stand-in device.
+ ///
+ /// Declared last so the values of the existing members are unchanged.
+ Unknown
}
-}
\ No newline at end of file
+}
diff --git a/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs b/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs
index 791c33d..331de17 100644
--- a/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs
+++ b/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs
@@ -3,38 +3,87 @@
using Android.Content;
using System.BluetoothLe;
using System.BluetoothLe.EventArgs;
+using Trace = System.BluetoothLe.Trace;
namespace System.BluetoothLe.BroadcastReceivers
{
- //[BroadcastReceiver]
+ ///
+ /// Receives the system's broadcast and reports it as a
+ /// .
+ ///
+ ///
+ /// The registers one of these for its lifetime and raises
+ /// from it, so an app does not need to register its own.
+ ///
public class BondStatusBroadcastReceiver : BroadcastReceiver
{
+ private readonly Adapter _adapter;
+
+ ///
+ /// Raised for every bond state change the system broadcasts, on the main thread.
+ ///
public event EventHandler BondStateChanged;
- public override void OnReceive(Context context, Intent intent)
+ ///
+ /// Creates a receiver that resolves devices through 's adapter.
+ ///
+ public BondStatusBroadcastReceiver()
{
- var bondState = (Bond)intent.GetIntExtra(BluetoothDevice.ExtraBondState, (int)Bond.None);
- //ToDo
- var device = new Device(null, (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice), null, 0);
- Console.WriteLine(bondState.ToString());
+ }
- if (BondStateChanged == null) return;
+ ///
+ /// Creates a receiver that resolves devices through and reports each change to it.
+ ///
+ internal BondStatusBroadcastReceiver(Adapter adapter)
+ {
+ _adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));
+ }
- switch (bondState)
+ ///
+ public override void OnReceive(Context context, Intent intent)
+ {
+ // OnReceive is called from the main looper: an exception escaping it terminates the process.
+ try
{
- case Bond.None:
- BondStateChanged(this, new DeviceBondStateChangedEventArgs(device, DeviceBondState.NotBonded));
- break;
+ if (intent?.Action != BluetoothDevice.ActionBondStateChanged)
+ {
+ return;
+ }
- case Bond.Bonding:
- BondStateChanged(this, new DeviceBondStateChangedEventArgs(device, DeviceBondState.Bonding));
- break;
+#pragma warning disable CA1422 // The typed overload is API 33+; the untyped one is the only one available below that.
+ var nativeDevice = OperatingSystem.IsAndroidVersionAtLeast(33)
+ ? (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice, Java.Lang.Class.FromType(typeof(BluetoothDevice)))
+ : (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
+#pragma warning restore CA1422
- case Bond.Bonded:
- BondStateChanged(this, new DeviceBondStateChangedEventArgs(device, DeviceBondState.Bonded));
- break;
+ if (nativeDevice == null)
+ {
+ return;
+ }
+ var bond = (Bond)intent.GetIntExtra(BluetoothDevice.ExtraBondState, (int)Bond.None);
+ var state = Device.ToBondState(bond);
+
+ var adapter = _adapter ?? BluetoothLE.Current.Adapter;
+ if (adapter == null)
+ {
+ Trace.Message("BondStatusBroadcastReceiver: No adapter is available to report the bond state change for {0}.", nativeDevice.Address);
+ return;
+ }
+
+ var device = adapter.ResolveDevice(nativeDevice);
+
+ if (_adapter != null)
+ {
+ _adapter.HandleBondStateChanged(device, state);
+ }
+
+ BondStateChanged?.Invoke(this, new DeviceBondStateChangedEventArgs(device, state));
+ }
+ catch (Exception ex)
+ {
+ Trace.Message("BondStatusBroadcastReceiver: Handling a bond state change failed: {0}", ex);
}
}
}
-}
\ No newline at end of file
+}
diff --git a/README.md b/README.md
index 05071ea..939eef1 100644
--- a/README.md
+++ b/README.md
@@ -219,6 +219,25 @@ await adapter.DisconnectDeviceAsync(device);
- `Service.GetCharacteristicsAsync`: discover GATT characteristics.
- `Characteristic.ReadAsync`, `WriteAsync`, `StartUpdatesAsync`, `StopUpdatesAsync`: interact with characteristic values.
- `Descriptor.ReadAsync`, `WriteAsync`: interact with descriptors.
+- `Device.BondState`: the device's bond (pairing) state, as the platform reports it.
+- `Adapter.DeviceBondStateChanged`: raised on Android when a device's bond state changes.
+
+## Bonding
+
+A peripheral that requires an encrypted link only answers a central it is bonded (paired) with. What an app can see of that bond depends on the platform.
+
+| Platform | `Device.BondState` | `Adapter.DeviceBondStateChanged` |
+| --- | --- | --- |
+| Android | `NotBonded`, `Bonding` or `Bonded`, read from the system on every call | Raised on the main thread for every bond change the system broadcasts, including changes made in the system Bluetooth settings |
+| iOS, macOS, Mac Catalyst, tvOS | Always `Unknown` | Never raised |
+| Windows | `Bonded` or `NotBonded`, from the device's pairing information | Never raised |
+| `net10.0` / `netstandard2.0` | Always `Unknown` | Never raised |
+
+**Apple platforms.** CoreBluetooth gives an app no way to read or request a bond. The operating system pairs on demand: the first time the app reads, writes or subscribes to a characteristic the peripheral protects, iOS shows the pairing prompt itself, and once the user accepts the link is encrypted for that and later operations. If the user declines, or the peripheral has lost its keys (for example after a factory reset), the operation fails, and the user has to remove the device in Settings > Bluetooth before pairing again. Design the app around attempting the protected operation and handling its failure, not around checking the bond first.
+
+**Android.** On Android 12 and later, reading the bond state and receiving bond changes both need the `BLUETOOTH_CONNECT` permission. Without it `BondState` reports `Unknown` and the event is not raised. Android, like Apple platforms, normally starts bonding by itself the first time a protected characteristic is accessed; `DeviceBondStateChanged` reports the outcome.
+
+`BondState` never throws: it reports `Unknown` wherever the state cannot be read, including for a stand-in device and after the device has been disposed.
## Notes