Skip to content

bluetooth

Yanxiang Yang edited this page Feb 19, 2016 · 3 revisions

Bluetooth

Bluetooth is a wireless technology standard for exchanging data over short distances.

  • Suggested Reading
  1. Bluetooth - Basic concepts of Bluetooth
  2. Serial Communication – Bluetooth is like a RF version of serial communication.
  3. Hexadecimal – Bluetooth devices all have a unique address, which is usually presented as a hexadecimal value.

Android API for Bluetooth

Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations:

  1. Scan for other Bluetooth devices
  2. Query the local Bluetooth adapter for paired Bluetooth devices
  3. Establish RFCOMM channels
  4. Connect to other devices through service discovery
  5. Transfer data to and from other devices
  6. Manage multiple connections

Turning on Bluetooth

You need to get Bluetooth adaptor:

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { // Device does not support Bluetooth }

If getDefaultAdapter() returns null, then the device does not support Bluetooth and your story ends here.

if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }

Turning off Bluetooth

we can just call the method .disable() of bluetooth adaptor.

mBluetoothAdapter.disable();

Querying paired devices

you can query all paired devices and then show the name of each device to the user:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } }

Enabling discoverability

Utilize startActivityForResult(Intent, int) with the ACTION_REQUEST_DISCOVERABLE action Intent to issue a request to enable discoverable mode through the system settings.

By default, the device will become discoverable for 120 seconds. You can define a different duration by adding the EXTRA_DISCOVERABLE_DURATION Intent extra.

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent);

Demo

Access the source code:

https://github.com/CourseReps/ECEN489-Spring2016/tree/master/Students/leoyyx2009/SimpleBluetoothExample

All of the Bluetooth APIs are available in the package:

Bluetooth APIs

Reference Link:

Bluetooth

Clone this wiki locally