[英]how to get all available bluetooth devices android c# xamarin
我想在列表視圖中獲取所有藍牙設備此代碼在java中工作但我想通過c#xamarin請求任何幫助嗎?
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
}
};
首先,在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
下面指定是標准的UUID
為SPP
:
_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.