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

问题描述:

我想获得列表视图中的所有蓝牙设备此代码在java中工作,但我想通过c#xamarin请任何帮助吗?如何获得所有可用的蓝牙设备android 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是标准UUIDSPP

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

现在,设备被连接时,通信经由InputStreamOutputStream性质,这住BluetoothSocket对象上这些属性是标准的.NET流对象发生和可以完全按照您的预期使用:

// 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);