im trying to make an app that connects to a bluetooth heart rate monitor. Ive searched so many articles and tutorials but they dont tell you how to setup or go into full detail about bluetooth. Does anybody know where to start this?
Do you mean you want connect to a Bluetooth Serial Device with Xamarin.Android ?
If yes ,
First, grab an instance of the default BluetoothAdapter
on the Android device and determine if it is enabled:
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.");
Next, get an instance of the BluetoothDevice
representing the physical device you're connecting to. You can get a list of currently paired devices using the adapter's BondedDevices
collection. I use some simple LINQ to find the device I'm looking for:
BluetoothDevice device = (from bd in adapter.BondedDevices
where bd.Name == "NameOfTheDevice" select bd).FirstOrDefault();
if(device == null)
throw new Exception("Named device not found.");
Finally, use the device's CreateRfCommSocketToServiceRecord
method, which will return a BluetoothSocket
that can be used for connection and communication. Note that the UUID specified below is the standard UUID for SPP:
_socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
await _socket.ConnectAsync();
Now that the device is connected, communication occurs via the InputStream
and OutputStream
properties which live on the BluetoothSocket object These properties are standard .NET Stream objects and can be used exactly as you'd expect:
// 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);
and you could refer to https://stackoverflow.com/a/51589235/10768653
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.