2017-07-27 131 views
1

我想獲得列表視圖中的所有藍牙設備此代碼在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 
    } 
} 

};

回答

0

首先,讓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);