How to pair Bluetooth device in Android Programmatically

The Android platform has popular hardware on every Android phone.it is mainly used for wirelessly exchanging data with another Bluetooth device.

The app framework provides Bluetooth functionality to access Bluetooth through Bluetooth API. These apps connect to other Bluetooth devices.

Let's discuss Bluetooth features.

  • Transfer data to and from other devices.
  • Paired Bluetooth on devices
  • Scan and connect to another device.
  • Establish RFCOMM  channels.
  • Manage more the one connection.
  • How to work Bluetooth on a mobile device
  • Setting up Bluetooth
  • Finding devices that are already paired or existing in the local area.
  • Connecting devices.
  • Send data between devices.
  • Classes and interfaces

1. Provide different methods and classes for connecting devices.

  •    Bluetooth adapter
  •    Bluetooth device
  •    Bluetooth Socket
  •    Bluetooth profile
  •    Bluetooth headset
  •    Bluetooth Health
  •    Bluetooth Health Callback
  •    Bluetooth Health App Configuration
  •    BluetoothProfile.ServiceListener

2. Flowing code for Bluetooth connection on a mobile device.


Step 1:  Create an object of Bluetooth adapter.

final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

Step 2: Check Bluetooth object is not null.

if (mBluetoothAdapter == null) { 

        out.append("device not supported");

      }

Step 3: On Bluetooth devices  in mobile devices.

if (!mBluetoothAdapter.isEnabled()) {

      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);         startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

 }

Step 4: Check your device is discoverable.

if (!mBluetoothAdapter.isDiscovering()) {

 //out.append("MAKING YOUR DEVICE DISCOVERABLE"); Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERABLE", Toast.LENGTH_LONG);

 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); 

startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT); 

}

Step 5: Turn Off Bluetooth.

 mBluetoothAdapter.disable();

 //out.append("TURN_OFF BLUETOOTH"); Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_LONG); 

}

In conclusion, while the Android system usually handles Bluetooth pairing automatically, you can now explore programmatic pairing for more advanced mobile application functionalities. Remember, this functionality might require extra permissions and user acknowledgment.



365Bloggy May 3, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive