Я создаю приложение, которое непрерывно сканирует устройства Bluetooth и фильтрует его по необработанным рекламным пакетам. Теперь устройство, от которого я хочу получать пакеты, не имеет возможности сопряжения. Оно ведет себя как маяк. Теперь проблема в том, что мне нужно, чтобы все устройства (1 в секунду) передавались с устройства, но сканирование по Bluetooth - дорогостоящий процесс, и ОС не позволяет сканированию продолжаться в течение длительного периода. Даже если я заставлю приложение сканировать в течение более длительного периода, я могу получить только 10-12 пакетов в минуту. И это зависит от устройства и версии Android.
Процесс сканирования получает каждое устройство Bluetooth, проверяет, является ли оно моим устройством, и сохраняет его в базе данных. Есть ли способ, с помощью которого я могу получать пакеты только с моего устройства, не подключаясь к нему?
Intent receiverIntent = new Intent(context, typeof(MyReceiver)); // explicite intent
receiverIntent.SetAction("com.company.ACTION_FOUND");
PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 1, receiverIntent, PendingIntentFlags.UpdateCurrent);
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
BluetoothLeScanner bluetoothLeScanner = adapter.BluetoothLeScanner;
ScanFilter filter = GetScanFilter();
List<ScanFilter> scanFilters = new List<ScanFilter>();
scanFilters.Add(filter);
mScanHandler.RemoveCallbacksAndMessages(null);
mScanHandler.Post(new Java.Lang.Runnable(() =>
{
try
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
bluetoothLeScanner.StartScan(scanFilters, GetScanSettings(), pendingIntent);
}
else
{
bluetoothLeScanner.StartScan(scanFilters, GetScanSettings(), scanCallback);
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}));
}
private ScanFilter GetScanFilter()
{
ScanFilter.Builder builder = new ScanFilter.Builder();
return builder.Build();
}
private ScanSettings GetScanSettings()
{
ScanSettings.Builder builder = new ScanSettings.Builder();
builder.SetScanMode(Android.Bluetooth.LE.ScanMode.LowLatency);
return builder.Build();
}
public class MScanCallBack : ScanCallback
{
public override void OnScanResult([GeneratedEnum] ScanCallbackType callbackType, Android.Bluetooth.LE.ScanResult result)
{
base.OnScanResult(callbackType, result);
Console.WriteLine("Scanning process: Device Found");
if (result != null)
{
var bytes = result.ScanRecord.GetBytes();
if (bytes[2] == 0xB0 && bytes[3] == 0xA0)
{
//Save data
}
}
}
public override void OnBatchScanResults(IList<Android.Bluetooth.LE.ScanResult> results)
{
base.OnBatchScanResults(results);
Console.WriteLine("Scanning process: OnBatchScanResults");
}
public override void OnScanFailed([GeneratedEnum] ScanFailure errorCode)
{
base.OnScanFailed(errorCode);
Console.WriteLine("Scanning process: Scan Failed" + errorCode.ToString());
}
}
[BroadcastReceiver]
[IntentFilter(new[] { "com.company.ACTION_FOUND" })]
public class MyReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Console.WriteLine("Scanning process: Device Found");
var action = intent.Action;
if (intent.HasExtra(BluetoothLeScanner.ExtraListScanResult))
{
var x = intent.GetParcelableArrayListExtra(BluetoothLeScanner.ExtraListScanResult);
var res = x.Cast<Android.Bluetooth.LE.ScanResult>().ToList();
foreach (var result in res)
{
var bytes = result.ScanRecord.GetBytes();
if (bytes[2] == 0xB0 && bytes[3] == 0xA0)
{
//Save Data
}
}
}
}
}