How do I actually BOND a device?

JuiCe picture JuiCe · Jun 7, 2012 · Viewed 17.3k times · Source

Everywhere I look I find this method "getBondedDevices()" for my bluetooth adapter. However, I have my tablet and another bluetooth device sitting next to me, and I can't figure out how to actually get the device to show up on the list of bonded devices.

Answer

devunwired picture devunwired · Jun 7, 2012

In Bluetooth terms, "bonded" and "paired" are basically synonyms (officially, the process of pairing leads to a bond, but most people use them interchangeable). In order for your device to be added to that list, you must go through the process of Discovery, which is how one device searches and finds another, and then Pair the two together.

You can actually do this from the device settings as a user, but if you are looking to so so within the context of an app, your process will likely look something like this:

  1. Register a BroadcastReceiver for BluetoothDevice.ACTION_FOUND and BluetoothAdapter. ACTION_DISCOVERY_FINISHED
  2. Start discovery by calling BluetoothAdapter.startDiscovery()
  3. Your receiver will get called with the first action every time a new device is found in range, and you can inspect it to see if it's the one you want to connect with. You can call BluetoothAdapter.cancelDiscovery() once you've found it to not waste the battery any more than necessary.
  4. When discovery is complete, if you haven't canceled it, your receiver will get called with the second action; so you know not to expect any more devices.
  5. With a device instance in hand, open a BluetoothSocket and connect(). If the devices are not already bonded, this will initiate pairing and may show some system UI for a PIN code.
  6. Once paired, your device will show up in the bonded devices list until the user goes into settings and removes it.
  7. The connect() method also actually opens the socket link, and when it returns without throwing an exception the two devices are connected.
  8. Now connected, you can call getInputStream() and getOutputStream() from the socket to read and write data.

Basically, you can inspect the list of bonded devices to quickly get access to an external device, but in most applications you will be doing a combination of this and true discovery to make sure you can always connect to the remote device regardless of what the user does. If a device is already bonded, you'd just be doing steps 5-7 to connect and communicate.

For more information and sample code, check out the "Discovering Devices" and "Connecting Devices" sections of the Android SDK Bluetooth Guide.

HTH