2017-07-27 22 views
1

私はリストビューでこのコードはJavaで動作しますが、私はC#xamarin任意の助けてそれをしたいすべてのBluetoothデバイスを取得したいですか?すべての利用可能なBluetoothデバイスを取得する方法

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コレクションを使用して、現在ペアになっているデバイスのリストを取得できます。接続および通信のために使用することができるBluetoothSocketを返しますデバイスのCreateRfCommSocketToServiceRecordメソッドを使用し、最後に

BluetoothDevice device = (from bd in adapter.BondedDevices 
          where bd.Name == "NameOfTheDevice" select bd).FirstOrDefault(); 

if(device == null) 
    throw new Exception("Named device not found."); 

:私は、私が探しているデバイスを見つけるために、いくつかの簡単なLINQを使用しています。

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

今デバイスが接続されていることを、通信BluetoothSocketオブジェクトに住んInputStreamOutputStreamプロパティを介して起こるこれらの特性は、標準.NETストリームオブジェクトであり、下記指定UUIDSPPための標準UUIDであることに注意してください期待どおりに正確に使用できます:

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