如何获得所有可用的蓝牙设备android c#xamarin

时间:2017-07-27 16:18:33

标签: c# android bluetooth xamarin.android

我想在列表视图中获取所有蓝牙设备此代码适用于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
    }
}

};

1 个答案:

答案 0 :(得分:1)

首先,在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。请注意,下面指定的UUIDUUID的标准SPP

_socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));  
await _socket.ConnectAsync();  

现在设备已连接,通过InputStream对象上的OutputStreamBluetoothSocket属性进行通信。这些属性是标准的.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);