To scan beacons in the background using Plugin.BLE in Xamarin.Forms, you can use the following steps:
<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>
public override void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
{
// Scanning code goes here.
completionHandler(UIBackgroundFetchResult.NewData);
}
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();
}
}
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);
}
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.
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
Asked: 2022-07-27 11:00:00 +0000
Seen: 13 times
Last updated: Apr 23 '21
How can Django Admin accommodate a variety of formats and locales for its input fields?
How can an array be passed using typo3 flexform xml and itemsProcConfig?
Is it possible to invoke an asynchronous function without using the await keyword?
How can metadata be linked to a series in Polars?
What is the process of utilizing the map function to map a pandas column using a dictionary?
How can the orientation of images be corrected during uploading using Plupload?