Android Bluetooth Tutorial

Bluetooth is a way to exchange data with other devices wirelessly. Android provides Bluetooth API to perform several tasks such as:

  • scan bluetooth devices
  • connect and transfer data from and to other devices
  • manage multiple connections etc.

Android Bluetooth API

The android.bluetooth package provides a lot of interfaces classes to work with bluetooth such as:

  • BluetoothAdapter
  • BluetoothDevice
  • BluetoothSocket
  • BluetoothServerSocket
  • BluetoothClass
  • BluetoothProfile
  • BluetoothProfile.ServiceListener
  • BluetoothHeadset
  • BluetoothA2dp
  • BluetoothHealth
  • BluetoothHealthCallback
  • BluetoothHealthAppConfiguration

android-preferences-example

BluetoothAdapter class

By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate device discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket instance to listen for connection requests etc.

Constants of BluetoothAdapter class

BluetoothAdapter class provides many constants. Some of them are as follows:

  • String ACTION_REQUEST_ENABLE
  • String ACTION_REQUEST_DISCOVERABLE
  • String ACTION_DISCOVERY_STARTED
  • String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class

Commonly used methods of BluetoothAdapter class are as follows:

  • static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of BluetoothAdapter.
  • boolean enable() enables the bluetooth adapter if it is disabled.
  • boolean isEnabled() returns true if the bluetooth adapter is enabled.
  • boolean disable() disables the bluetooth adapter if it is enabled.
  • String getName() returns the name of the bluetooth adapter.
  • boolean setName(String name) changes the bluetooth name.
  • int getState() returns the current state of the local bluetooth adapter.
  • Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded) BluetoothDevice objects.
  • boolean startDiscovery() starts the discovery process.

Android Bluetooth Example: enable, disable and make discovrable bluetooth programmatically

You need to write few lines of code only, to enable or disable the bluetooth.

activity_main.xml

Drag one textview and three buttons from the pallete, now the activity_main.xml file will like this:

File: activity_main.xml

Provide Permission

You need to provide following permissions in AndroidManifest.xml file.

The full code of AndroidManifest.xml file is given below.

File: AndroidManifest.xml

Activity class

Let's write the code to enable, disable and make bluetooth discoverable.

File: MainActivity.java


You need to run it on the real device (e.g. mobile) to test the application.


Next topics of android bluetooth tutorial:

android bluetooth list paired devices example







Latest Courses