Hello,
My issues start happening once I reconnect to the device in the event the connection is lost (device turns off/on or too far away).
Please implement the DeviceConnectionLost event, if the connection is lost, this event will be invoked, you can use adapter.ConnectToKnownDeviceAsync(deviceId);
method to reconnect it.
adapter.DeviceConnectionLost += Adapter_DeviceConnectionLost;
private void Adapter_DeviceDisconnected(object? sender, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs e)
{
AttemptReconnect(e.Device.Id);
}
async void AttemptReconnect(Guid deviceId)
{
try
{
//show loading dialog or smth
await adapter.ConnectToKnownDeviceAsync(deviceId);
//
}
catch (TaskCanceledException e)
{
//do nothing, task was cancelled
}
catch (Exception ex)
{
//retry, android will throw a GATT 133 error if device is still not in range, ios willl try indefinately
AttemptReconnect(deviceId);
}
finally
{
//hide loading
}
}
By the way, do not forget to add following runtime permissions(permissions are runtime permissions. Therefore, you must explicitly request user approval in your app before you can look for Bluetooth devices).
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
I test it in Android devices and use BLE to connect to the iPhone devices, If I turn off the iPhone devices's bluetooth and reopen it, DeviceConnectionLost will be executed and reconnect it.
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.