簡體   English   中英

使用 Xamarin.android 中的 BluetoothAdapter 執行藍牙掃描

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

我正在用 Xamarin 實現一個 APP。

我想執行藍牙掃描。 並找到設備。

這是我的代碼。

一旦觸發“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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM