[英]Xamarin Android Bluetooth Connection
我正在嘗試制作一個連接到藍牙心率監測器的應用程序。 我搜索了很多文章和教程,但它們沒有告訴您如何設置或詳細介紹藍牙。 有人知道從哪里開始嗎?
您的意思是要使用 Xamarin.Android 連接到藍牙串行設備嗎?
如果是 ,
首先,在 Android 設備上獲取默認BluetoothAdapter
的實例,並確定它是否已啟用:
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
if(adapter == null)
throw new Exception("No Bluetooth adapter found.");
if(!adapter.IsEnabled)
throw new Exception("Bluetooth adapter is not enabled.");
接下來,獲取代表您要連接的物理設備的BluetoothDevice
實例。 您可以使用適配器的BondedDevices
集合獲取當前配對設備的列表。 我使用一些簡單的 LINQ 來查找我正在尋找的設備:
BluetoothDevice device = (from bd in adapter.BondedDevices
where bd.Name == "NameOfTheDevice" select bd).FirstOrDefault();
if(device == null)
throw new Exception("Named device not found.");
最后,使用設備的CreateRfCommSocketToServiceRecord
方法,該方法將返回一個可用於連接和通信的BluetoothSocket
。 請注意,下面指定的 UUID 是 SPP 的標准 UUID:
_socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
await _socket.ConnectAsync();
現在設備已連接,通過存在於 BluetoothSocket 對象上的InputStream
和OutputStream
屬性進行通信。這些屬性是標准的 .NET Stream 對象,可以完全按照您的預期使用:
// Read data from the device
await _socket.InputStream.ReadAsync(buffer, 0, buffer.Length);
// Write data to the device
await _socket.OutputStream.WriteAsync(buffer, 0, buffer.Length);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.