Sunday, September 4, 2016

BluetoothAdapter ActionDiscoveryFinished

Leave a Comment

I just started to take a look at xamarin and now I want to scan for bluetooth-devices. Therefor I use the following code:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter; bluetoothAdapter.StartDiscovery(); 

And I have the following class for getting the result:

[BroadcastReceiver] [IntentFilter(new [] {BluetoothAdapter.ActionDiscoveryFinished})] public class BluetoothReceiver : BroadcastReceiver {     public BluetoothReceiver()     {      }      public override void OnReceive(Context context, Intent intent)     {         if (BluetoothAdapter.ActionDiscoveryFinished.Equals(intent.Action))         {          }     } } 

I've also set the permissions for my app to BLUETOOTH and BLUETOOTH_ADMIN. Everything just works fine and the OnReceive-Method is called correctly. My problem now is: How do I get the found devices from the parameters of the OnReceive-Method?

1 Answers

Answers 1

ACTION_DISCOVERY_FINISHED doesn't tell you anything other than the discovery action has finished. https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#ACTION_DISCOVERY_FINISHED

If you wanted to grab devices from the scan, you should read what startDiscovery() has to say regarding finding devices:

The discovery process usually involves an inquiry scan of about 12 seconds, followed by a page scan of each new device to retrieve its Bluetooth name.

This is an asynchronous call, it will return immediately. Register for ACTION_DISCOVERY_STARTED and ACTION_DISCOVERY_FINISHED intents to determine exactly when the discovery starts and completes. Register for ACTION_FOUND to be notified as remote Bluetooth devices are found.

https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery()

Thus you should use ACTION_FOUND and parse the EXTRA_DEVICE for devices:

Broadcast Action: Remote device discovered.

Sent when a remote device is found during discovery.

Always contains the extra fields EXTRA_DEVICE and EXTRA_CLASS. Can contain the extra fields EXTRA_NAME and/or EXTRA_RSSI if they are available.

https://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#ACTION_FOUND

In sequence of events, you would do the following:

  1. ACTION_DISCOVERY_STARTED - Which will start discovery
  2. ACTION_FOUND - Which will find a device
  3. ACTION_DISCOVERY_FINISHED - Which will end discovery
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment