Bluetooth

August 10,2016

Android provides Bluetooth API to perform these different operations.

  • Scan for other Bluetooth devices
  • Get a list of paired devices
  • Connect to other devices through service discovery

Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below.

private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();

In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);

Apart from this constant, there are other constants provided the API , that supports different tasks. They are listed below.

Sr.No Constant & description
1 ACTION_REQUEST_DISCOVERABLE

This constant is used for turn on discovering of bluetooth

2 ACTION_STATE_CHANGED

This constant will notify that Bluetooth state has been changed

3 ACTION_FOUND

This constant is used for receiving information about each device that is discovered

Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.

private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

Apart form the parried Devices , there are other methods in the API that gives more control over Blueetooth. They are listed below.

Sr.No Method & description
1 enable()

This method enables the adapter if not enabled

2 isEnabled()

This method returns true if adapter is enabled

3 disable()

This method disables the adapter

4 getName()

This method returns the name of the Bluetooth adapter

5 setName(String name)

This method changes the Bluetooth name

6 getState()

This method returns the current state of the Bluetooth Adapter.

7 startDiscovery()

This method starts the discovery process of the Bluetooth for 120 seconds.

Leave a comment