如何在Android C# Xamarin中获取所有可用的蓝牙设备

4
我想在列表视图中获取所有蓝牙设备,在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个回答

4
首先,在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对象上的InputStreamOutputStream属性进行。这些属性是标准的.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);  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接