Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To scan beacons in the background using Plugin.BLE in Xamarin.Forms, you can use the following steps:

  1. Add the Plugin.BLE package to your Xamarin.Forms project.
  2. Check if the device supports background modes and Bluetooth in Info.plist file, if it's needed required use this code.
<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
</array>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Your description here</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Your description here</string>
  1. Register the BLE background task in the AppDelegate.cs file using:
public override void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
{
    // Scanning code goes here.
    completionHandler(UIBackgroundFetchResult.NewData);
}
  1. Create a separate class for doing the background scanning work, and call it from the registered BLE background task:
public class BackgroundScanner
{
    private IBluetoothLE ble;
    private IAdapter adapter;
    private CancellationTokenSource tokenSource;

    public async Task StartScan()
    {
        try
        {
            tokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(500));

            // Retrieve the BluetoothLE interface.
            ble = CrossBluetoothLE.Current;

            // Retrieve the adapter.
            adapter = CrossBluetoothLE.Current.Adapter;

            // Scan for devices.
            adapter.DeviceDiscovered += Adapter_DeviceDiscovered;
            await adapter.StartScanningForDevicesAsync(tokenSource.Token);
        }
        catch (Exception ex)
        {
            // Handle any exceptions here.
        }
    }

    private void Adapter_DeviceDiscovered(object sender, DeviceEventArgs e)
    {
        // Handle the discovered devices here.
    }

    public async Task StopScan()
    {
        await adapter.StopScanningForDevicesAsync();
    }
}
  1. In the PerformFetch method, call the StartScan method of the BackgroundScanner class and pass the completion handler.
public override void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
{
    var scanner = new BackgroundScanner();

    Task.Factory.StartNew(async () =>
    {
        await scanner.StartScan();

        completionHandler(UIBackgroundFetchResult.NewData);

        await scanner.StopScan();

    }, TaskCreationOptions.LongRunning);
}
  1. Finally, register the PerformFetch method in the UIApplication.Main method:
public static class MainClass
{
    public static void Main(string[] args)
    {
        UIApplication.Main(args, null, "AppDelegate");
    }
}

This will start scanning beacons in the background using Plugin.BLE in Xamarin.Forms.