在 Xamarin.android 中使用 BluetoothAdapter 执行蓝牙扫描

Perform a bluetooth scan with BluetoothAdapter in Xamarin.android

我正在用 Xamarin 实现一个应用程序。

我想执行蓝牙扫描。并找到设备。

这是我的代码。

我如何实现它以启动扫描并在触发“Button_Scan()”后收集结果?

谢谢。

[BroadcastReceiver(Enabled = true)]
public class BluetoothReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var action = intent.Action;

        if (action != BluetoothDevice.ActionFound)
        {
            return;
        }

        if (BluetoothDevice.ActionFound.Equals(action))
        {
            var device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
            var ConnectState = device.BondState;
            /*
            switch (ConnectState)
            {
                case Bond.None:
                    break;
                case Bond.Bonded:
                    break;
                case Bond.Bonding:
                    break;
            }
            */

            if (device.Name != null)
            {
                Xamarin.Forms.Application.Current.MainPage.DisplayAlert("Found device", device.Name, "ok");
            }
        }
    }
}


public async void Button_Scan(object sender, EventArgs e)
{
    try
    {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
        mBluetoothAdapter.Enable();

        mBluetoothAdapter.StartDiscovery();
    }
    catch(Exception ex)
    {
        DisplayAlert("ex", ex.ToString(), "ok");
    }
}

您已经定义了一个BluetoothReceiver来接收结果,您只需将设备信息添加到一个deviceList即可。

 public static List<string> mDeviceList = new List<string>();

 public override void OnReceive(Context context, Intent intent)
    {
        string action = intent.Action;
        if (BluetoothDevice.ActionFound.Equals(action))
        {
            BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
            mDeviceList.Add(device.Name + ";" + device.Address);             
        }
    } 

别忘了注册广播。

BluetoothReceiverreceiver = new BluetoothReceiver();
IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound);
RegisterReceiver(receiver, filter);