Android provides Bluetooth API to perform several tasks such as:

  • Scanning bluetooth devices.
  • Display list of paired devices.
  • Enable Bluetooth on a device.
  • connect and transfer data from and to other devices.

How to enable Bluetooth in device?

public final static int REQUEST_BLUETOOTH = 1; Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBTIntent,REQUEST_BLUETOOTH);

How to get  Bluetooth Adapter class to communicate with Bluetooth?

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

How to get List of Paired Bluetooth in Android?

Set bluetoothDevices = bluetoothAdapters.getBondedDevices();

List of important predefined constants in Bluetooth API?

String ACTION_REQUEST_ENABLE : Show a system activity that allows the user to turn on Bluetooth.
String ACTION_REQUEST_DISCOVERABLE : To make android device as Discoverable mode.
String ACTION_DISCOVERY_STARTED : The local Bluetooth adapter has started the remote device discovery process.
String ACTION_DISCOVERY_FINISHED : The local Bluetooth adapter has finished the device discovery process.
String ACTION_STATE_CHANGED : notify that Bluetooth state has been changed
String  ACTION_FOUND : Sent when a remote device is found during discovery

What are all the permissions needed ?

Connect,Disconnect,Transfer Data
uses-permission android:name=“android.permission.BLUETOOTH” />

Disover new devices,Change BT settings
uses-permission android:name=“android.permission.BLUETOOTH_ADMIN” />

Example ::

All above explained functionalities are  available in this Github code

Output Screen :






How to do Scanning?

  • For Discovering nearby devices,invoke startDiscovery() method.
  • For Stopping Discovery ,invoke cancelDiscovery()
  • Discovery takes up lot of resources,If you want to connect to other bluetooth devices,You must stop discovery before connecting.

Role of Broadcast Receiver in Scanning?

  • You have to register receiver when you call startDiscovery()
  • Unregister that when you call cancelDiscovery()
  • Whenever we found Bluetooth device, BluetoothDevice.ACTION_FOUND action will be called.we can handle this action Inside onReceive() of BroadcastReceiver.

BroadcastReceiver scanBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.i(TAG,” action “+intent.getAction()); if (BluetoothDevice.ACTION_FOUND.equals(action)){ BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); } };

Example ::

All Scanning related  functionalities are  available in this Github code

Output Screen :