Search code examples
androidxamarinxamarin.androidbluetoothbluetoothadapter

Perform a bluetooth scan with BluetoothAdapter in Xamarin.android


I am implementing an APP with Xamarin.

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?

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

Solution

  • You have defined a BluetoothReceiver to receive the result ,you just add the device information into a 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);