简体   繁体   English

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

[英]Perform a bluetooth scan with BluetoothAdapter in Xamarin.android

I am implementing an APP with Xamarin.我正在用 Xamarin 实现一个 APP。

I want to perform a Bluetooth scan.我想执行蓝牙扫描。 And get the device found.并找到设备。

Here is my code.这是我的代码。

How could I implement this to start a scan and collect the result once"Button_Scan()" is triggered?一旦触发“Button_Scan()”,我该如何实现它来开始扫描并收集结果?

Thank you.谢谢你。

[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");
    }
}

You have defined a BluetoothReceiver to receive the result,you just add the device information into a deviceList .您已经定义了一个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);             
        }
    } 

Don't forget to regist the broadcast.不要忘记注册广播。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM