Ask Your Question
1

What is the method for scanning beacons in the background using Plugin.BLE in Xamarin Forms?

asked 2022-07-27 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-04-23 01:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-27 11:00:00 +0000

Seen: 13 times

Last updated: Apr 23 '21